简体   繁体   中英

Why I get a "Access is denied" error by Spring Security and Keycloak?

I setup a Keycloak server with Docker. Configured the realm and client and so on. I managed successfully to write a Spring Boot service for some RestControllers. Work so on.

But when I try to use Spring Security with Keycloak Adapter, I'm stuck.

Here is my SecurityConfig:

@KeycloakConfiguration
class SecurityConfig : KeycloakWebSecurityConfigurerAdapter() {

    @Autowired
    lateinit var keycloakClientRequestFactory: KeycloakClientRequestFactory

    @Bean
    fun keycloakConfigResolver(): KeycloakSpringBootConfigResolver = KeycloakSpringBootConfigResolver()

    @Bean
    override fun sessionAuthenticationStrategy(): SessionAuthenticationStrategy =
        NullAuthenticatedSessionStrategy()

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

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        super.configure(http)
        http.cors().disable()
            .csrf().disable()
            .exceptionHandling().and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
            .formLogin().disable()
            .authorizeRequests()
            .antMatchers("/apps/manual-data-collection/**").hasRole("user")
            .anyRequest().permitAll()
    }

    /**
     * https://www.keycloak.org/docs/latest/securing_apps/index.html#avoid-double-bean-registration
     */
    @Bean
    @ConditionalOnMissingBean(HttpSessionManager::class)
    override fun httpSessionManager(): HttpSessionManager = HttpSessionManager()

}

Now I try the access the server, but get a 403 Forbidden Error. Following is log by spring:

2020-01-08 14:08:01.817 DEBUG 12396 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/apps/manual-data-collection/document-templates'; against '/apps/manual-data-collection/**'
2020-01-08 14:08:01.817 DEBUG 12396 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /apps/manual-data-collection/document-templates; Attributes: [hasRole('ROLE_user')]
2020-01-08 14:08:01.817 DEBUG 12396 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@bc432bbc: Principal: willy; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@42db7613; Not granted any authorities
2020-01-08 14:08:01.818 DEBUG 12396 --- [nio-8080-exec-5] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@3d0602a7, returned: -1
2020-01-08 14:08:01.818 DEBUG 12396 --- [nio-8080-exec-5] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is not anonymous); delegating to AccessDeniedHandler

org.springframework.security.access.AccessDeniedException: Access is denied

What confuse me is, that it says: Not granted any authorities . If I leave out the part, everything works fine. The necessary roles (in this case 'user') are stored in the realm. The JWT token also provides these. I have no idea why it wouldn't work.

Edit: Which I should mention. The Spring Boot Server should only be used as a REST server for an Angular application and is therefore STATELESS .

Okay, I found my mistake. I had activated the following in the application.yml:

keycloak.use-resource-role-mappings=true

But it must be false . Keycloak documentation say's following:

use-resource-role-mappings - If set to true, the adapter will look inside the token for application level role mappings for the user. If false, it will look at the realm level for user role mappings. This is OPTIONAL. The default value is false.

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