简体   繁体   中英

Spring Boot Oauth2 authorization server not accepting valid tokens

I have problems setting up a simple microservice system using Spring Boot's OAuth2 capabilities.

What I want to do is to set up a Spring Boot Authorization Server handling registration, authorization and user data management. Besides that, I'd like to set up a Resource Server handling the logic of the application.

Because all data is stored related to the user's ID, the resource server has to request the ID from authorization server. Therefore, I've set up the following user info endpoint:

@Controller
public class UserInfoEndpoint {

    private UserManagementBean userManagementBean;

    @Autowired
    public UserInfoEndpoint(final UserManagementBean userManagementBean) {
        this.userManagementBean = userManagementBean;
    }

    @GetMapping("/user/me")
    @ResponseBody
    public Principal user(final Principal principal) throws PRPException {
        User user = userManagementBean.loadUser(principal.getName());
        @SuppressWarnings("unused")
        Principal retVal = new Principal() {

            @Override
            public String getName() {
                return user.getId().toString();
            }

            public String getPrimaryEmail() {
                return user.getPrimaryEmail();
            }
        };
        return retVal;
    }

}

At the moment, I'm using JWK to sign the tokens. I am able to access this endpoint with Postman, where I get the following result:

{
    "primaryEmail": "eric@live.de",
    "name": "3"
}

However, when trying to obtain user information with the resource server

    @Bean
    @RequestScope
    public OAuth2Authentication userInfo(final HttpServletRequest request) {
        UserInfoTokenServices services = new UserInfoTokenServices("http://localhost:8081/user/me", "PRPBackend");
        services.setPrincipalExtractor(principalExtractor());

        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        String tokenString = authHeader.replace("Bearer ", "").replace("bearer ", "");
        DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenString);

        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
        resource.setAccessTokenUri("http://localhost:8081/oauth/token");
        resource.setClientId("PRPBackend");
        resource.setClientSecret("secret");
        resource.setUserAuthorizationUri("http://localhost:8081/oauth/authorize");
        resource.setAuthenticationScheme(AuthenticationScheme.header);
        resource.setClientAuthenticationScheme(AuthenticationScheme.header);

        OAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
        clientContext.setPreservedState("key", "abcdef");
        clientContext.setAccessToken(accessToken);

        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, clientContext);
        services.setRestTemplate(restTemplate);

        OAuth2Authentication authentication = services.loadAuthentication(tokenString);

        return authentication;
    }

the authorization server tells me, that the user is anonymous.

2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 4 of 13 in additional filter chain; firing Filter: 'CorsFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 5 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 6 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/me' doesn't match 'POST /logout'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 7 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/me' doesn't match 'POST /login'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@74903b51: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /user/me at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/actuator/**'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/favicon.ico'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/login'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/confirm/**'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/signup'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/oauth/authorize'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/css/**'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/me'; against '/img/**'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/me' doesn't match 'OPTIONS /oauth/token'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/me' doesn't match 'POST /oauth/token'
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /user/me; Attributes: [authenticated]
2019-12-16 06:28:30.532 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@74903b51: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2019-12-16 06:28:30.533 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@33824388, returned: -1
2019-12-16 06:28:30.545 DEBUG 7018 --- [nio-8081-exec-2] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) [spring-boot-actuator-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at com.prp.auth.security.filter.SimpleCorsFilter.doFilter(SimpleCorsFilter.java:38) [main/:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_222]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_222]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_222]

and returns the login page.

I've tried several configs, but nothing worked. Here's my security config of the authorization server:

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // @formatter:off
        http.requestMatchers().and()
        .authorizeRequests()
        .and()
        .authorizeRequests()
        .antMatchers("/actuator/**", "/favicon.ico").permitAll()
        .antMatchers(HttpMethod.GET, "/login", "/confirm/**", "/signup",
                "/oauth/authorize", "/css/**", "/img/**").permitAll()
        .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
        .antMatchers(HttpMethod.POST, "/oauth/token").permitAll()
        .and().formLogin().loginPage("/login").permitAll()
        .and().authorizeRequests().anyRequest().authenticated()
        .and().headers().frameOptions().disable()
        .and().cors().configurationSource(new CorsConfigurationSource() {

                    @Override
                    public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
                        CorsConfiguration conf = new CorsConfiguration();
                        List<String> allowedOrigins = new ArrayList<>();
                        allowedOrigins.add("http://localhost:8000");
                        conf.setAllowedOrigins(allowedOrigins);
                        List<String> allowedMethods = new ArrayList<>();
                        allowedMethods.add("POST");
                        conf.setAllowedMethods(allowedMethods);
                        return conf;
                    }
                });
}

EDIT :

I've been trying to access the same endpoint via Postman and JQuery. Postman is able to fetch the user's data, the JQuery implementation gets the same error as described above.

One more edit:

The JQuery request I'm testing with is the following:

  fetchUser() {
    let ref = this;
    console.log("Calling URL to load user information: " + localStorageManager.loadOauthProvider() + "/user/me");
    $.ajax({
      url: localStorageManager.loadOauthProvider() + "/user/me",
      method: "GET",
      headers: ref.oauth2.authorizationHeader,
      success: function(data, status, xhr) {
        console.log("Fetch user response: " + JSON.stringify(data));
      },
      error: function(xhr, status, error) {
        console.log("Error: " + error);
      }
    });
  }

The result:

Fetch user response: "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\"\n\tcontent=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n<meta name=\"description\" content=\"\">\n<meta name=\"author\" content=\"\">\n<link rel=\"icon\" href=\"/img/favicon.ico\">\n\n<title>Login</title>\n<link rel=\"stylesheet\"\n\thref=\"/css/bootstrap.min.css\" />\n\n<!-- Custom styles for this template -->\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/login.css\" />\n\n</head>\n\n<body class=\"text-center\">\n\n\t<form name=\"login\" action=\"/login\" method=\"post\"\n\t\tclass=\"form-signin\">\n\t\t<h1 class=\"h3 mb-3 font-weight-normal\">LEVO</h1>\n\t\t<img class=\"mb-4\" src=\"/img/logo.png\" alt=\"\" width=\"72\"\n\t\t\theight=\"72\">\n\t\t<h1 class=\"h3 mb-3 font-weight-normal\">\n\t\t\t<span>Anmelden</span>\n\t\t</h1>\n\t\t\n\t\t\n\t\t<label for=\"username\" class=\"sr-only\">E-Mail</label>\n\t\t<input type=\"text\" id=\"username\" name=\"username\" class=\"form-control\"\n\t\t\tplaceholder=\"E-Mail\" required autofocus>\n\t\t<label for=\"password\" class=\"sr-only\"></label>\n\t\t<input type=\"password\" id=\"password\" name=\"password\"\n\t\t\tclass=\"form-control\" placeholder=\"Passwort\"\n\t\t\trequired>\n\t\t<div class=\"checkbox mb-3\">\n\t\t\t<label> <input type=\"checkbox\" value=\"remember-me\"> <span>Angemeldet bleiben</span>\n\t\t\t</label>\n\t\t</div>\n\t\t<button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">\n\t\t\t<span>Anmelden</span>\n\t\t</button>\n\t\t<a class=\"nav-link\" href=\"/signup\">\n\t\t\t<span data-feather=\"home\"></span>\n\t\t\t<span>Hier registrieren</span>\n\t\t</a>\n\n\t\t<p class=\"mt-5 mb-3 text-muted\">&copy; Levo 2019</p>\n\t</form>\n\n\n</body>\n</html>"

Postman is creating the following request, which works:

GET /user/me HTTP/1.1 Host: localhost:8081 Authorization: Bearer [...]

From my point of view your SecurityConfig handles not what you expect. Your first rule http.requestMatchers().and().authorizeRequests() means:

requestMatchers() configures if an URL will be processed by that SecurityFilterChain. So if an URL does not match it , the whole SecurityFilterChain will be skipped which means Spring Security will not handle this URL after that. If you do not configure it, the default is to match all URLs.

So you need to define your antMatchers Resources which should be processed by this SecurityFilerChain. If you change this rule to the following basic config http.requestMatchers().antMatchers("/")... the user endpoint should work as expected.

The reason behind this is, that the endpoint /user/me should not be handled/overridden by this SecurityConfigChain. So if you have enabled the ResourceServer of Spring in a default way, the default config is used for this endpoint.

So in this antMatchers("/") you should define all resources which should be handled by this security filter but not the user/me .

You have both @EnableAuthorizationServer , @EnableResourceServer in AuthServerConfig which might be causing the issue. Remove @EnableResourceServer as you are extending the AuthorizationServerConfigurerAdapter with AuthServerConfig

Change

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter

To

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM