OAuth: Bekomme die E-Mail-Adresse des Benutzers nicht

RezaScript

Bekanntes Mitglied
Hallo, ich habe ein Problem mit OAuth. Ich kann mich über Google zwar einloggen, bekomme aber die E-Mail-Adresse nicht.

Ich benutze diese Dependency in Spring Boot:
XML:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
    <version>3.0.4</version>
</dependency>

Nach dem Login wird der User weitergeleitet zu diesem Controller:
Java:
@Controller
public class OAuthController {
    @GetMapping("/google")
    public ResponseEntity<String> google() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication instanceof OAuth2AuthenticationToken) {
            OAuth2User user = (OAuth2User) authentication.getPrincipal();

            String email = user.getAttribute("email");
            System.out.println(email);
        } else {
            System.out.println("No Email");
        }

        return ResponseEntity.ok("Hello");
    }

Ich komme aber immer nur im Else-Statement. authentication gibt folgendes aus:

2023-10-25 11_25_49-quotations-backend_bk – OAuthController.java [dq].png

Und meine Security-Konfiguration sieht so aus:

Java:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy());

    http.authorizeHttpRequests(auth ->
            auth
                    .requestMatchers("/api/welcome").authenticated()
                    .anyRequest().permitAll()
    );

    http.httpBasic();
    http.logout().permitAll();
    http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    http.oauth2Login(Customizer.withDefaults());
    return http.build();
}

Was stimmt mit meinem Code nicht?

PS: Sorry, der Beitrag müsste eigentlich hier hin.
 
Zuletzt bearbeitet:

Robert Zenz

Top Contributor
authentication gibt folgendes aus:

2023-10-25 11_25_49-quotations-backend_bk – OAuthController.java [dq].png
Das ist auch ein nicht-angemeldeter Benutzer (**Anonymous**AuthenticationToken).

Und meine Security-Konfiguration sieht so aus:

Java:
Code:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy());

    http.authorizeHttpRequests(auth ->
            auth
                    .requestMatchers("/api/welcome").authenticated()
                    .anyRequest().permitAll()
    );

    http.httpBasic();
    http.logout().permitAll();
    http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    http.oauth2Login(Customizer.withDefaults());
    return http.build();
}
Ich bin mir da nie ganz sicher (furchtbares Spring-Teil) aber ich glaueb der oauth2login Aufruf muss direkt auf authorizeHttpRequests folgen. Im Moment wirkt OAuth2 naemlich auf...mh...gar nichts? Oder eben auf irgendetwas folgen das den "Wirkungsbereich" angibt.
 

RezaScript

Bekanntes Mitglied
Hmm, das bringt mich leider nicht weiter. So sieht es aus, nachdem der User sich mit einem Google-Account eingeloggt hat:

2023-10-26T13:21:30.344+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@70b0dc92, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@309d54ac, org.springframework.security.web.context.SecurityContextHolderFilter@d863bb, org.springframework.security.web.header.HeaderWriterFilter@aca2a0b, org.springframework.security.web.authentication.logout.LogoutFilter@2446be5f, org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter@7ff7e353, org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter@70680f88, com.dynamicquatation.dq.config.JwtFilter@2ee5c08d, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@fd5c7f6, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@390978, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@751b901a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4560eb15, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@b4c89b6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@561c031, org.springframework.security.web.session.SessionManagementFilter@2cdb53d6, org.springframework.security.web.access.ExceptionTranslationFilter@7945986a, org.springframework.security.web.access.intercept.AuthorizationFilter@1f7b1d6a]] (1/1)
2023-10-26T13:21:30.344+02:00 DEBUG 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Securing GET /google?state=GD20nMezMYXerPKSYqlyz_JEC6Fc57pVGan1Jzy0MTE%3D&code=4%2F0AfJohXnol0FG1OU5-l74Gcm0mMwAxLIkDBvA3vn77nCfJPYgRzyYrqN6PFM3zm4rjJcZDA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent
2023-10-26T13:21:30.344+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/17)
2023-10-26T13:21:30.344+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/17)
2023-10-26T13:21:30.345+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/17)
2023-10-26T13:21:30.345+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/17)
2023-10-26T13:21:30.345+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking LogoutFilter (5/17)
2023-10-26T13:21:30.345+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.s.w.a.logout.LogoutFilter : Did not match request to Or [Ant [pattern='/logout', GET], Ant [pattern='/logout', POST], Ant [pattern='/logout', PUT], Ant [pattern='/logout', DELETE]]
2023-10-26T13:21:30.346+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking OAuth2AuthorizationRequestRedirectFilter (6/17)
2023-10-26T13:21:30.346+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking OAuth2LoginAuthenticationFilter (7/17)
2023-10-26T13:21:30.346+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking JwtFilter (8/17)
2023-10-26T13:21:30.346+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking DefaultLoginPageGeneratingFilter (9/17)
2023-10-26T13:21:30.347+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking DefaultLogoutPageGeneratingFilter (10/17)
2023-10-26T13:21:30.349+02:00 TRACE 39104 --- [nio-8080-exec-5] .w.a.u.DefaultLogoutPageGeneratingFilter : Did not render default logout page since request did not match [Ant [pattern='/logout', GET]]
2023-10-26T13:21:30.349+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking BasicAuthenticationFilter (11/17)
2023-10-26T13:21:30.349+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.s.w.a.www.BasicAuthenticationFilter : Did not process authentication request since failed to find username and password in Basic Authorization header
2023-10-26T13:21:30.350+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking RequestCacheAwareFilter (12/17)
2023-10-26T13:21:30.352+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.s.w.s.HttpSessionRequestCache : matchingRequestParameterName is required for getMatchingRequest to lookup a value, but not provided
2023-10-26T13:21:30.352+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderAwareRequestFilter (13/17)
2023-10-26T13:21:30.356+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking AnonymousAuthenticationFilter (14/17)
2023-10-26T13:21:30.357+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking SessionManagementFilter (15/17)
2023-10-26T13:21:30.357+02:00 TRACE 39104 --- [nio-8080-exec-5] w.c.HttpSessionSecurityContextRepository : Did not find SecurityContext in HttpSession C6D3829E22A9217734152F48DB583B1C using the SPRING_SECURITY_CONTEXT session attribute
2023-10-26T13:21:30.358+02:00 TRACE 39104 --- [nio-8080-exec-5] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
2023-10-26T13:21:30.358+02:00 TRACE 39104 --- [nio-8080-exec-5] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
2023-10-26T13:21:30.360+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=C6D3829E22A9217734152F48DB583B1C], Granted Authorities=[ROLE_ANONYMOUS]]
2023-10-26T13:21:30.360+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking ExceptionTranslationFilter (16/17)
2023-10-26T13:21:30.360+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Invoking AuthorizationFilter (17/17)
2023-10-26T13:21:30.361+02:00 TRACE 39104 --- [nio-8080-exec-5] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@4b308f58]
2023-10-26T13:21:30.377+02:00 TRACE 39104 --- [nio-8080-exec-5] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@4b308f58] using org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer$$Lambda$1291/0x0000000801826570@6d7dab88
2023-10-26T13:21:30.378+02:00 DEBUG 39104 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Secured GET /google?state=GD20nMezMYXerPKSYqlyz_JEC6Fc57pVGan1Jzy0MTE%3D&code=4%2F0AfJohXnol0FG1OU5-l74Gcm0mMwAxLIkDBvA3vn77nCfJPYgRzyYrqN6PFM3zm4rjJcZDA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent
No Email
2023-10-26T13:21:30.405+02:00 TRACE 39104 --- [nio-8080-exec-5] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match request to [Is Secure]
 

RezaScript

Bekanntes Mitglied
Ok, ich habe herausgefunden, dass ich einen logischen Fehler hatte.

Das

Java:
    http.authorizeHttpRequests(auth ->
            auth
                    .requestMatchers("/api/welcome").authenticated()
                    .anyRequest().permitAll()
    );

habe ich durch

Java:
http.authorizeHttpRequests(auth ->
    auth
        .requestMatchers("/").permitAll()
        .anyRequest().authenticated()
);

ersetzt. Funktioniert bestens.
 

Neue Themen


Oben