当前位置: 首页 > 知识库问答 >
问题:

Spring Security密钥斗篷:接受承载令牌

孙宏扬
2023-03-14

不知何故,我迷失了Spring Security和Keycloak。

在一个应用程序中,我成功地从KeyClope实例接收了一个访问令牌。然后,我使用这个令牌请求我的Spring Security服务器(它使用相同的KeyClope实例)。

但我得到的只是403个错误。

以下是代码摘录(用kotlin编写):

安全配置

@KeycloakConfiguration
abstract class MyConfig : KeycloakWebSecurityConfigurerAdapter() {

   @Autowired
   lateinit var keycloakClientRequestFactory: KeycloakClientRequestFactory

   @Bean
   @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
   fun keycloakRestTemplate(): KeycloakRestTemplate {
      return KeycloakRestTemplate(keycloakClientRequestFactory)
   }

   @Autowired
   @Throws(Exception::class)
   fun configureGlobal(auth: AuthenticationManagerBuilder) {
      val keycloakAuthenticationProvider = keycloakAuthenticationProvider()
      keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(SimpleAuthorityMapper())
      auth.authenticationProvider(keycloakAuthenticationProvider)
   }

   @Bean
   fun KeycloakConfigResolver(): KeycloakConfigResolver {
      return KeycloakSpringBootConfigResolver()
   }

   @Throws(Exception::class)
   override fun configure(http: HttpSecurity) {
      http.csrf().disable()
        .cors().and()
        .authorizeRequests()
        .anyRequest().authenticated()
      http.requiresChannel().anyRequest().requiresSecure()
   }

   @Bean
   override fun sessionAuthenticationStrategy(): SessionAuthenticationStrategy =
      RegisterSessionAuthenticationStrategy(SessionRegistryImpl())

   @Bean
   fun keycloakAuthenticationProcessingFilterRegistrationBean(
      filter: KeycloakAuthenticationProcessingFilter): FilterRegistrationBean {
      val registrationBean = FilterRegistrationBean(filter)
      registrationBean.isEnabled = false
      return registrationBean
   }

   @Bean
   fun keycloakPreAuthActionsFilterRegistrationBean(
      filter: KeycloakPreAuthActionsFilter): FilterRegistrationBean {
      val registrationBean = FilterRegistrationBean(filter)
      registrationBean.isEnabled = false
      return registrationBean
   }

   @Bean
   fun corsConfigurationSource(): CorsConfigurationSource {
      val configuration = CorsConfiguration()
      configuration.allowedOrigins = arrayListOf("*").toMutableList()
      configuration.allowedMethods = arrayListOf("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS")
      configuration.allowCredentials = true
      configuration.allowedHeaders = arrayListOf("Authorization", "Cache-Control", "Content-Type")
      val source = UrlBasedCorsConfigurationSource()
      source.registerCorsConfiguration("/**", configuration)
      return source
   }
}

在我的控制器中:

   @RequestMapping("/test")
   @ResponseBody
   fun test(): String {
      return "success"
   }

在我对服务器的调用中,我可以验证授权头的设置如下:authorization:Bearer[Token]

我错过了什么?我很高兴能得到任何帮助!

编辑:

Spring Security调试日志:

2018-02-13 15:37:37.594 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /maintenance/secure-test; Attributes: [authenticated]
2018-02-13 15:37:37.594 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055286a: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@59b2: RemoteIpAddress: 192.168.1.4; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2018-02-13 15:37:37.595 DEBUG 13245 --- [io-10010-exec-3] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2018-02-13 15:37:37.595 DEBUG 13245 --- [io-10010-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-02-13 15:37:37.595 DEBUG 13245 --- [io-10010-exec-1] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6b79755c, returned: -1
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] 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-4.2.3.RELEASE.jar:4.2.3.RELEASE]
        at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
[...skipping full stack trace...]

2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']]
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/maintenance/secure-test'; against '/**/favicon.ico'
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = true
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@40c8c1fa, matchingMediaTypes=[application/json], useEquals=false, ignoredMediaTypes=[*/*]]]
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : httpRequestMediaTypes=[application/json, text/plain, */*]
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : Processing application/json
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : application/json .isCompatibleWith application/json = true
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = false
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access
2018-02-13 15:37:37.596 DEBUG 13245 --- [io-10010-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-02-13 15:37:37.597 DEBUG 13245 --- [io-10010-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

KeyClope调试(在Spring服务器上):

2018-02-13 17:29:46.455 DEBUG 14194 --- [io-10010-exec-8] o.k.adapters.PreAuthActionsHandler       : adminRequest [URI]/maintenance/secure-test
2018-02-13 17:29:46.455 DEBUG 14194 --- [io-10010-exec-8] .k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /maintenance/secure-test
2018-02-13 17:29:46.455 DEBUG 14194 --- [io-10010-exec-8] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke [URI]/maintenance/secure-test
2018-02-13 17:29:46.455 DEBUG 14194 --- [io-10010-exec-8] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
2018-02-13 17:29:46.461 DEBUG 14194 --- [io-10010-exec-9] o.k.adapters.PreAuthActionsHandler       : adminRequest [URI]/maintenance/secure-test
2018-02-13 17:29:46.462 DEBUG 14194 --- [io-10010-exec-9] .k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /maintenance/secure-test
2018-02-13 17:29:46.462 DEBUG 14194 --- [io-10010-exec-9] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke [URI]/maintenance/secure-test
2018-02-13 17:29:46.462 DEBUG 14194 --- [io-10010-exec-9] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
2018-02-13 17:29:46.463 DEBUG 14194 --- [io-10010-exec-9] o.k.adapters.PreAuthActionsHandler       : adminRequest [URI]/maintenance/secure-test
2018-02-13 17:29:46.463 DEBUG 14194 --- [io-10010-exec-9] f.KeycloakAuthenticationProcessingFilter : Request is to process authentication
2018-02-13 17:29:46.463 DEBUG 14194 --- [io-10010-exec-9] f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication
2018-02-13 17:29:46.467 DEBUG 14194 --- [io-10010-exec-9] o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
2018-02-13 17:29:46.572 DEBUG 14194 --- [io-10010-exec-9] o.k.a.rotation.JWKPublicKeyLocator       : Realm public keys successfully retrieved for client service-api. New kids: [omitted KID]
2018-02-13 17:29:46.573 DEBUG 14194 --- [io-10010-exec-9] o.k.a.BearerTokenRequestAuthenticator    : successful authorized
2018-02-13 17:29:46.577 DEBUG 14194 --- [io-10010-exec-9] a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: []
2018-02-13 17:29:46.578 DEBUG 14194 --- [io-10010-exec-9] o.k.adapters.RequestAuthenticator        : User ’test' invoking ‚[URI]/maintenance/secure-test' on client 'service-api'
2018-02-13 17:29:46.578 DEBUG 14194 --- [io-10010-exec-9] o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
2018-02-13 17:29:46.578 DEBUG 14194 --- [io-10010-exec-9] f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
2018-02-13 17:29:46.586 DEBUG 14194 --- [io-10010-exec-9] o.k.a.s.management.HttpSessionManager    : Session created: [omitted sessione ID]
2018-02-13 17:29:46.588 DEBUG 14194 --- [io-10010-exec-9] f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@bb340ce7: Principal: test; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@68bb9634; Not granted any authorities
2018-02-13 17:29:46.588 DEBUG 14194 --- [io-10010-exec-9] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke [URI]/maintenance/secure-test
2018-02-13 17:29:46.588 DEBUG 14194 --- [io-10010-exec-9] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.

共有1个答案

全卜霸
2023-03-14

为了完整起见,我回答这个问题:

就像在一篇关于这个问题的评论中所说的那样,问题在于调用super。在keydepowebsecurityConfigureAdapter中配置(http)

因此,如果您在进行此调用时遇到类似的错误检查。配置应该如下所示:

@KeycloakConfiguration
class MyConfig : KeycloakWebSecurityConfigurerAdapter() {
   // [...]
   @Throws(Exception::class)
   override fun configure(http: HttpSecurity) {
      super.configure(http) // this call was missing
      // [...]
   }
}
 类似资料:
  • 我正在尝试在API网关(Apache APISIX)后面使用KeyClope。 我使用minikube来运行KeyClope和API网关。 网关正常工作,KeyClope也正常工作: 使用KeyClope,我可以使用不同的endpoint(使用发现endpoint(http://127.0.0.1:7070/auth/realms/myrealm/.well-已知/uma2配置),询问访问令牌并进

  • 我有java REST应用程序,我希望通过keycloak保护。我做了一些测试,应用程序与keycloak servlet过滤器配合良好,但我在Spring Security适配器方面遇到了问题。 钥匙斗篷。json(删除值) 可见,我只需要承载授权,若请求包含有效令牌,那个么若不是http 401,那个么我希望是http 200。我使用了以下xml配置: 到底发生了什么?请求经过身份验证,但成功

  • 谁知道如何使用获取id_令牌? 我一直在(Spring,JEE)和postman中与合作。 基本的工作正常,但我需要,因为有一些声明,它们不存在于中,但它们存在于中。 使用库,我可以获得Keycloak上下文,但id_token属性始终为null。 有什么主意吗?

  • 我试图使用Keycloak的openId-connectendpoint来获取关于用户角色的信息。我使用/auth/realms/moje/protocol/OpenID-connect/userinfoendpoint来获取关于已验证用户的信息。我可以获得姓名、用户名、电子邮件等信息。但是我不能强迫Keyclak给我关于用户角色的信息。 我已经阅读了openID文档,我没有找到任何关于必须获取角

  • 有角度的v.v4。0.2 Spring靴1.5版。2.发布 钥匙斗篷v.2。4.0.最终版本(稍后将升级) 我读了关于同样问题的邮件对话:http://keycloak-user.88327.x6.nabble.com/keycloak-user-NOT-ATTEMPTED-bearer-only-error-while-trying-to-access-server-from-client-td

  • 我们有一个角度水疗中心,是由OIDC授权使用隐式流。我们使用Keycloak作为我们的授权服务器。访问令牌的寿命很短,并且通过隐藏的iframe定期刷新。 在了解到授权代码流PKCE是授权SPA的新推荐方式后,我们决定切换流。一切正常,但每次我们调用令牌endpoint时,KeyCloak确实会给我们一个刷新令牌(以及Access和ID-Token)。由于没有安全的方法来存储刷新令牌,我们想继续使