Невозможно использовать вход в Google в Spring SecurityJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Невозможно использовать вход в Google в Spring Security

Сообщение Anonymous »

Я пытаюсь использовать Spring Security, чтобы включить вход через Google в мое приложение. У меня применена следующая конфигурация:

Код: Выделить всё

@Configuration
@EnableWebSecurity(debug=true)
public class SpringConfig {

Logger logger = Logger.getLogger("MyLogger");

@Bean
public SecurityFilterChain filterChain(HttpSecurity http)  throws Exception {
http
.csrf(Customizer.withDefaults())
.oauth2Login(Customizer.withDefaults())
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
);

SecurityFilterChain chain = http.build();
return chain;
}

private ClientRegistration googleClientRegistration() {

return ClientRegistration.withRegistrationId("google")
.clientId("yyy")
.clientSecret("xxx")
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
.issuerUri("https://accounts.google.com")
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.redirectUri("http://localhost:8080/app/login/oauth2/code/google")
.scope("openid", "email", "profile")
.tokenUri("https://oauth2.googleapis.com/token")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.build();
}

@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
}
Я перепроверил все значения. По какой-то причине, которую я не смог выяснить, я постоянно получаю эту ошибку после аутентификации в Google:

Код: Выделить всё

[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: Error while extracting response for type [class org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse] and content type [application/json;charset=utf-8]
Я создал небольшое приложение на Python, которое выполняет этот поток OpenID Connect с помощью простых запросов, и, похоже, оно отлично работает именно с этими значениями. Что здесь не так?
Отладка
Я включил javax.net.debug=all, вижу, что запрос на конечная точка доступа получает действительный ответ, который включает в себя как токен идентификатора, так и токен доступа. Токен доступа выглядит следующим образом:

Код: Выделить всё

{
"issued_to": "xxx.apps.googleusercontent.com",
"audience": "xxx.apps.googleusercontent.com",
"user_id": "xxx45",
"scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
"expires_in": 2864,
"email": "me@gmail.com",
"verified_email": true,
"access_type": "online"
}
Похоже, что сообщение об ошибке подразумевает, что этот токен доступа нельзя преобразовать в объект OAuth2AccessTokenResponse или что-то подобное.
Может кто-нибудь поможет?

Подробнее здесь: https://stackoverflow.com/questions/793 ... g-security
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»