【问题标题】:Spring Security returns 403 with valid JWTSpring Security 使用有效的 JWT 返回 403
【发布时间】:2020-08-04 08:13:09
【问题描述】:

我正在使用 Postman 测试我在 Spring Boot 2.2.6 中使用 Spring Security 创建的简单 OAuth2 API。我在请求新用户凭据时成功接收到 JWT,但是当我尝试在我的标头中使用此令牌访问它们时,我的所有端点都返回 403 Forbidden 错误。

我的课如下:

我的服务器安全配置:

@Configuration
@EnableWebSecurity
@Order(1)
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
class ServerSecurityConfiguration(
        @Qualifier("userService")
        private val userDetailsService: UserDetailsService
) : WebSecurityConfigurerAdapter() {
    private val logger: Logger = LoggerFactory.getLogger(ServerSecurityConfiguration::class.java)

    @Bean
    fun authenticationProvider(): DaoAuthenticationProvider {
        val provider = DaoAuthenticationProvider()
        provider.setPasswordEncoder(passwordEncoder())
        provider.setUserDetailsService(userDetailsService)

        return provider
    }

    @Bean
    fun passwordEncoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }

    @Bean
    @Throws(Exception::class)
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    @Throws(Exception::class)
    override fun configure(auth: AuthenticationManagerBuilder) {
        auth
            .parentAuthenticationManager(authenticationManagerBean())
            .authenticationProvider(authenticationProvider())
            .userDetailsService(userDetailsService)
            .and()
    }

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http
            .cors().and().csrf().disable() // remove for production
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
                .authorizeRequests()
                    .antMatchers(
                            "/",
                            "/index.html",
                            "/**/*.js",
                            "/**/*.html",
                            "/**/*.css",
                            "/**/*.woff",
                            "/**/*.woff2",
                            "/**/*.svg",
                            "/**/*.ttf",
                            "/**/*.ico",
                            "/**/*.eot",
                            "/**/assets/*",
                            "/api/login/**",
                            "/oauth/token",
                            "/oauth/authorize"
                    )
                        .permitAll()
                    .antMatchers(HttpMethod.POST, "/api/submissions")
                        .authenticated()
                    .antMatchers(HttpMethod.POST, "/api/users")
                        .hasAuthority(Role.ADMIN.name)
                    .antMatchers(HttpMethod.POST,"/api/**")
                        .hasAuthority(Role.ADMIN.name)
                    .antMatchers(HttpMethod.DELETE, "/api/**")
                        .hasAuthority(Role.ADMIN.name)
                    .antMatchers(HttpMethod.PUT, "/api/**")
                        .hasAnyAuthority(Role.ADMIN.name)
                    .antMatchers(HttpMethod.GET, "/api/**")
                        .authenticated()
                    .anyRequest()
                        .authenticated()
    }
}

我的 OAuth2 配置:

@Configuration
@EnableAuthorizationServer
class OAuth2Configuration(
        @Qualifier("authenticationManagerBean") private val authenticationManager: AuthenticationManager,
        private val passwordEncoder: PasswordEncoder,
        private val userService: UserService,
        private val jwt: JwtProperties
) : AuthorizationServerConfigurerAdapter() {
    private val logger = LoggerFactory.getLogger("OAuth2Configuration")

    @Throws(Exception::class)
    override fun configure(clients: ClientDetailsServiceConfigurer?) {
        clients
            ?.inMemory()
            ?.withClient(jwt.clientId)
            ?.secret(passwordEncoder.encode(jwt.clientSecret))
            ?.accessTokenValiditySeconds(jwt.accessTokenValiditySeconds)
            ?.refreshTokenValiditySeconds(jwt.refreshTokenValiditySeconds)
            ?.authorizedGrantTypes(*jwt.authorizedGrantTypes)
            ?.scopes("read", "write")
            ?.resourceIds("api")
    }

    override fun configure(endpoints: AuthorizationServerEndpointsConfigurer?) {
        endpoints
            ?.tokenStore(tokenStore())
            ?.accessTokenConverter(accessTokenConverter())
            ?.userDetailsService(userService)
            ?.authenticationManager(authenticationManager)
    }

    @Bean
    fun accessTokenConverter(): JwtAccessTokenConverter {
        val converter = JwtAccessTokenConverter()
        converter.setSigningKey(jwt.signingKey)

        return converter
    }

    @Bean
    @Primary
    fun tokenServices(): DefaultTokenServices {
        val services = DefaultTokenServices()
        services.setTokenStore(tokenStore())

        return services
    }

    @Bean
    fun tokenStore(): JwtTokenStore {
        return JwtTokenStore(accessTokenConverter())
    }
}

我的资源服务器配置:

@Configuration
@EnableResourceServer
class ResourceServerConfiguration : ResourceServerConfigurerAdapter() {
    override fun configure(resources: ResourceServerSecurityConfigurer?) {
        resources?.resourceId("api")
    }
}

我的用户详情服务:

@Service
class UserService(private val repository: UserRepository) : UserDetailsService {
    private val logger: Logger = LoggerFactory.getLogger(UserService::class.java)

    override fun loadUserByUsername(username: String?): UserDetails {
        val user = repository.findByUsername(username)
                ?: throw UserNotFoundException("User with username $username not found.")

        return org.springframework.security.core.userdetails.User
            .withUsername(user.name)
            .password(user.passwordHash)
            .authorities(user.role.name)
            .build()
    }
}

任何帮助将不胜感激,我在这里不知所措。


调试日志如下:

2020-04-21 08:05:42.583 DEBUG 14388 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/submissions'; against '/api/**'
2020-04-21 08:05:42.583 DEBUG 14388 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /api/submissions; Attributes: [authenticated]
2020-04-21 08:05:42.584 DEBUG 14388 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@ac165fba: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2020-04-21 08:05:42.584 DEBUG 14388 --- [nio-8080-exec-3] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@1097cbf1, returned: -1
2020-04-21 08:05:42.601 DEBUG 14388 --- [nio-8080-exec-3] 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.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123) ~[spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.33.jar:9.0.33]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

我的用户对象似乎没有获得 ADMIN 角色。


更新: 我添加了一个过滤器并打印出不记名令牌。它确实存在。

【问题讨论】:

  • 您将不得不经历开启 Spring Security 调试日志并尝试破译其内容的艰苦过程。在准备过程中,我建议你做一些让你开心的事情。吃垃圾食品什么的。 stackoverflow.com/questions/30855252/…
  • 从您提供的内容中我可以猜到您的 ResourceServerConfigurerAdapter 不够用。您当前已将所有规则放在 WebSecurityConfigurerAdapter 类中,但它的工作原理是,只要 JWT 令牌成为请求的一部分,ResourceServerConfigurerAdapter 类就会“接管”并定义安全规则。很可能,如果您将网络安全中的规则复制到资源服务器安全类中,事情就会开始发挥作用。
  • 另外说明:使用 EnableResourceServer 和 EnableAuthorizationServer 被认为是过时的,最终可能会在明年放弃对它的支持。 spring.io/blog/2019/11/14/…
  • 好的,听起来我需要改用@EnableOAuth2Client 吗?它是否注释了两个类?我似乎无法解释这方面的文档。
  • 您要么想要修复现有的东西,要么想要迁移——两个完全不同的问题。迁移肯定需要 10 多分钟的研究工作。尤其是当您意识到 EnableAuthorizationServer 支持已被完全删除而不是被新的 API 取代时。

标签: spring-boot kotlin spring-security


【解决方案1】:

添加以下过滤器似乎可以解决问题。

class JwtAuthorizationFilter(
        authenticationManager: AuthenticationManager,
        @Qualifier("userService")
        private val userDetailsService: UserService,
        private val jwt: JwtProperties,
        private val passwordEncoder: PasswordEncoder

) : BasicAuthenticationFilter(authenticationManager) {
    private val log: Logger = LoggerFactory.getLogger(JwtAuthorizationFilter::class.java)

    @Throws(ServletException::class, IOException::class)
    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
        val header = request
            .getHeader(jwt.authorizationHeaderString)
            ?.takeIf { s -> s.startsWith(jwt.tokenBearerPrefix) }

        if (header == null) {
            filterChain.doFilter(request, response)
            return
        }

        val auth = authenticate(request)

        if (auth != null) {
            log.info("Authentication valid for ${auth.principal}.")
            SecurityContextHolder.getContext().authentication = auth
        }

        log.info("Bearer token processed. Continue.")
        filterChain.doFilter(request, response)
    }

    private fun authenticate(request: HttpServletRequest): UsernamePasswordAuthenticationToken? {
        val token = request.getHeader(jwt.authorizationHeaderString)

        if (token != null) {
            val claims = JWT
                .require(Algorithm.HMAC256(jwt.signingKey))
                .build()
                .verify(token.replace("${jwt.tokenBearerPrefix} ", ""))
                .claims

            val username = claims["user_name"]?.asString()
            val authorities = claims["authorities"]
                    ?.asArray(String::class.java)
                    ?.map { s -> SimpleGrantedAuthority(s) }
                    ?: return null

            if (username != null) {
                return UsernamePasswordAuthenticationToken(username, null, authorities)
            }
        }

        return null
    }
}

你需要追加

            .and()
                .addFilter(
                        JwtAuthorizationFilter(authenticationManager(), userDetailsService as UserService, jwt, passwordEncoder())
                )

到您的服务器安全 HTTP 配置。

【讨论】:

    【解决方案2】:

    有点晚了,但更简单的解决方案可能是创建自定义 Jwt 身份验证转换器:

    class CustomJwtAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
    
      private val jwtGrantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
    
      override fun convert(source: Jwt): AbstractAuthenticationToken {
        val scopes = jwtGrantedAuthoritiesConverter.convert(source)
        val authorities = source.getClaimAsStringList("authorities")?.map { SimpleGrantedAuthority(it) }
        return JwtAuthenticationToken(source, scopes.orEmpty() + authorities.orEmpty())
      }
    }
    

    然后将转换器提供给您的override fun configure(http: HttpSecurity) 实现,例如:

    .jwtAuthenticationConverter(CustomJwtAuthenticationConverter())
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 2020-04-20
      • 2018-09-09
      • 2015-10-23
      • 2018-08-28
      • 2018-11-06
      • 2020-07-31
      • 2022-12-07
      • 2015-11-04
      相关资源
      最近更新 更多