繁体   English   中英

如何在 Spring Boot Oauth2 授权服务器中 grant_type=client_credentials 时抛出错误凭据的任何异常

[英]How to throw any Exceptions for wrong credentials when grant_type=client_credentials in Spring Boot Oauth2 Authorization Server

我正在尝试在同一个应用程序中设置authorization serverresource server grant_type=client_credentials ,对于正确的client_idclient_secret配置有效。 但是对于错误的凭据,默认情况下它不会抛出有用的异常。 以下是错误凭据的错误消息。

{
    "timestamp": 1605701863451,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/login"
}

我想要一些HTTP status=400 ,例如-

{
    "error": "invalid_grant",
    "error_description": "Bad credentials"
}

我的配置

文件名:AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    public CustomTokenEnhancer customTokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory().withClient("android-client")
                .authorizedGrantTypes("client_credentials", "password","refresh_token")
                .scopes("read", "write", "trust")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(600000)
                .secret(CustomConfiugration.getPasswordEncoder().encode("android-secret"))
                .refreshTokenValiditySeconds(-1);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST)
                .tokenEnhancer( this.customTokenEnhancer())
                .tokenStore(this.tokenStore())
                .userDetailsService(customUserDetailsService);
    }
}

文件名:CustomUserDetailsS​​ervice.java

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    public UserRepository userRepository;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Bad credentials");
        }
        return user;
    }
}

文件名:WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/static/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(customUserDetailsService)
                .passwordEncoder( CustomConfiugration.getPasswordEncoder());
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .failureUrl("/login?error")
                .permitAll();
        http
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .deleteCookies("JSESSIONID")
                .permitAll();
    }
}

编辑:忘了把调试日志。 这里是,

2020-11-18 18:47:49.426 DEBUG 5228 --- [nio-8080-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /oauth/token
2020-11-18 18:47:49.426 DEBUG 5228 --- [nio-8080-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/oauth/token]
2020-11-18 18:47:49.426 DEBUG 5228 --- [nio-8080-exec-9] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/token
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] .s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException]
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/resources/static/**'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token']
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/token'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : matched
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /oauth/token?grant_type=client_credentials at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /oauth/token?grant_type=client_credentials at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /oauth/token?grant_type=client_credentials at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /oauth/token?grant_type=client_credentials at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', GET]
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /oauth/token' doesn't match 'GET /logout
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', POST]
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/logout'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', PUT]
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /oauth/token' doesn't match 'PUT /logout
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', DELETE]
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /oauth/token' doesn't match 'DELETE /logout
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /oauth/token?grant_type=client_credentials at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.a.www.BasicAuthenticationFilter  : Basic Authentication Authorization header found for user 'android-clients'
2020-11-18 18:47:49.427 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2020-11-18 18:47:49.497 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.a.dao.DaoAuthenticationProvider    : User 'android-clients' not found
2020-11-18 18:47:49.497 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.a.www.BasicAuthenticationFilter  : Authentication request for failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
2020-11-18 18:47:49.497 DEBUG 5228 --- [nio-8080-exec-9] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2020-11-18 18:47:49.497 DEBUG 5228 --- [nio-8080-exec-9] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@5ffdd228
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@7894676
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/resources/static/**'
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token']
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/oauth/token'
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token_key']
2020-11-18 18:47:49.498 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/oauth/token_key'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/check_token']
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/oauth/check_token'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/api/**'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@4e2ebfa8. A new one will be created.
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', GET]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'GET /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', POST]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/logout'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', PUT]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'PUT /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', DELETE]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'DELETE /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/login'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : queryString: arg1=grant_type=client_credentials; arg2=grant_type=client_credentials (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/error; arg2=/error (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : serverPort: arg1=8080; arg2=8080 (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : requestURL: arg1=http://localhost:8080/error; arg2=http://localhost:8080/error (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : scheme: arg1=http; arg2=http (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : serverName: arg1=localhost; arg2=localhost (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : contextPath: arg1=; arg2= (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.DefaultSavedRequest            : servletPath: arg1=/error; arg2=/error (property equals)
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.s.HttpSessionRequestCache        : Removing DefaultSavedRequest from session if present
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@93157775: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 38BE5E2B0F39371468B6392F305F022D; Granted Authorities: ROLE_ANONYMOUS'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /error?grant_type=client_credentials at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', GET]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'GET /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', POST]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/logout'
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', PUT]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'PUT /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', DELETE]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'DELETE /logout
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /error?grant_type=client_credentials; Attributes: [authenticated]
2020-11-18 18:47:49.499 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@93157775: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 38BE5E2B0F39371468B6392F305F022D; Granted Authorities: ROLE_ANONYMOUS
2020-11-18 18:47:49.500 DEBUG 5228 --- [nio-8080-exec-9] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@ebb7516, returned: -1
2020-11-18 18:47:49.500 DEBUG 5228 --- [nio-8080-exec-9] 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.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_272]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_272]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_272]

邮递员请求:请求格式与错误的客户端凭据

你应该像下面这样抛出自定义异常:---

public class UserValidException extends Exception{

void UserValidException (Exception e){
super(e);
}
}

在您的代码之前:--

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Bad credentials");
        }
        return user;
    }

后: -

@Override
    public UserDetails loadUserByUsername(String username) throws UserValidException {

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UserValidException ("Bad credentials");
        }
        return user;
    }

现在您需要使用其他类中的异常处理程序来处理这些异常,例如:--

@SuppressWarnings({"rawtypes","unchecked"})
@ControlerAdvice
public class CustomUserDetailsServiceExceptionHandler extends ResponseEntityExceptionHandler{

@ExceptionHandler(value=UserValidException.class){
protected ResponseEntity<ErrorInfo> handleUserValidException(UserValidException ex){
ErrorInfo error = new ErrorInfo();
error.setError("invalid_grant");
error.SetError_description("Bad credentials");
return new ResponseEntity<ErrorInfo>(error ,HttpStatus.INTERNAL_SERVER_ERROR);
}
}

public class ErrorInfo {

    private String error;
    private String error_description;
    
//Setter
//Getter
}

方法二:---

当 user=null 时,您会抛出“错误凭据”消息;

然后直接使用以下代码捕获此消息:--

    @SuppressWarnings({"rawtypes","unchecked"})
     @ControlerAdvice
     public class CustomUserDetailsServiceExceptionHandler extends 
 ResponseEntityExceptionHandler{
            
        @ExceptionHandler(value=UsernameNotFoundException.class){
        protected ResponseEntity<ErrorInfo> handleUsernameNotFoundException(UsernameNotFoundException ex){
          ErrorInfo error = new ErrorInfo();
    if(ex.getMessage().equals("Bad credentials"){
            error.setError("invalid_grant");
            error.SetError_description("Bad credentials");
            return new ResponseEntity<ErrorInfo>(error ,HttpStatus.INTERNAL_SERVER_ERROR);
            }
            }

定义模型类:--

public class ErrorInfo {
    
        private String error;
        private String error_description;
        
    //Setter
    //Getter
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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