KeycloakSecurityContext在SpringBoot中返回null

时间:2019-03-27 19:13:42

标签: java spring-boot keycloak

我正在使用Keycloak 5,Spring Boot 2和Angular 7创建SPA。

一切都很好,即使application.properties中的密钥克隆配置和角色安全也是如此。但是,当我尝试创建一个Bean来获取用户令牌数据时,我收到的是一个空Bean。不明白为什么,就像Keycloak文档中的代码...

import javax.servlet.http.HttpServletRequest;

import org.keycloak.KeycloakSecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Configuration
public class KeycloakConfig {

    /**
     * Retorna o contexto de segurança do Keycloak.
     * 
     * @return
     */
    @Bean
    @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public KeycloakSecurityContext accessToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    }
}

启动配置:

    keycloak.enabled                    = true
    keycloak.auth-server-url            = http://acesso.tre-pa.jus.br/auth
    keycloak.realm                      = TRE-PA
    keycloak.resource                   = acesso-sistemas-service
    keycloak.credentials.secret         = ca70294a-af51-4abb-81f9-234566de2c7c
    keycloak.ssl-required               = external
    keycloak.use-resource-role-mappings = false
    keycloak.bearer-only                = true
    keycloak.autodetect-bearer-only     = true
    keycloak.principal-attribute        = preferred_username
    logging.level.org.keycloak          = DEBUG 

    spring.main.allow-bean-definition-overriding = true

    # spring.autoconfigure.exclude        = org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration

    keycloak.securityConstraints[0].securityCollections[0].name        = secured-area
    keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /secured/*
    keycloak.securityConstraints[1].securityCollections[0].patterns[1] = /admin/*

    keycloak.securityConstraints[1].authRoles[0]                       = DEVELOPER
    keycloak.securityConstraints[1].securityCollections[0].name        = service-area
    keycloak.securityConstraints[1].securityCollections[0].patterns[0] = /service/*

0 个答案:

没有答案