春季无法获取keycloak授权令牌
Posted
技术标签:
【中文标题】春季无法获取keycloak授权令牌【英文标题】:Can not get keycloak authorization token in spring 【发布时间】:2019-06-19 07:07:04 【问题描述】:我有网络应用程序,我正在尝试制作 keycloak
authorizations
在 javascript 方面,我将进入 keycloak
登录页面并成功验证。这是我的代码
var keycloak = Keycloak(
realm: 'demo',
url: 'localhost:8080/auth',
clientId: 'justice'
);
keycloak.init( onLoad: 'login-required' ).success(function(authenticated)
alert(authenticated ? 'authenticated' : 'not authenticated');
).error(function()
alert('failed to initialize');
);
然后我在java
一边打电话给Rest web service
$.ajax(
type: "POST",
url: "login",
headers:
"Authorization":"Bearer "+ keycloak.token
,
success: function (response)
location.reload();
,
error: function (jqXHR, textStatus, errorThrown)
console.log(textStatus, errorThrown);
);
这里一切正常,我正在获取令牌并放入标头,但我在 java 端有问题,不能从 token
中获取 authorization token
、user role
和其他一些 properties
。
这是我的configuration
类,它使用spring security config
import javax.servlet.http.HttpServletRequest;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory;
import org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
@Autowired
KeycloakClientRequestFactory keycloakClientRequestFactory;
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy()
return new NullAuthenticatedSessionStrategy();
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public KeycloakRestTemplate keycloakRestTemplate()
return new KeycloakRestTemplate(keycloakClientRequestFactory);
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
@Override
protected void configure(HttpSecurity http) throws Exception
super.configure(http);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and().authorizeRequests()
.antMatchers("/login*").hasRole("ADMIN").anyRequest().permitAll();
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken getAccessToken()
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
return ((KeycloakAuthenticationToken) request.getUserPrincipal()).getAccount().getKeycloakSecurityContext()
.getToken();
那我想拿token但是每次尝试都没用。
我试过这种方式,结果为空
@Controller
@RequestMapping
public class AuthController
@Autowired
private AccessToken accessToken;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verify(Principal principal,Model model) throws Exception
//principal field is null
String token = accessToken.getAccessTokenHash(); // null
这样
@Controller
@RequestMapping
public class AuthController
@Autowired
private AccessToken accessToken;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verify(Principal principal,Model model) throws Exception
Authentication auth =SecurityContextHolder.getContext().getAuthentication();
KeycloakPrincipal principal = (KeycloakPrincipal) auth.getPrincipal(); // again null
这样也是
@Controller
@RequestMapping
public class AuthController
@Autowired
private AccessToken accessToken;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verify(Principal principal,Model model) throws Exception
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
AuthorizationContext authzContext = keycloakSecurityContext.getAuthorizationContext(); // and still null
这是我的keycloak.json
的内容,放在WEB-INF
中
"realm": "demo",
"bearer-only": true,
"auth-server-url": "localhost:8080/auth",
"ssl-required": "external",
"resource": "justice-service",
"use-resource-role-mappings": true
也许我误解了这个authentication
或其他东西的流程。也许我在代码或configuration
中有一些错误。我只需要从此令牌中获取token
和properties
,即java 端的用户角色或用户名。我第一次使用keycloak authentication
,无论如何我需要像我一样在JavaScript
和Java
一侧设置这个Adapters
吗?还是只有JavaScript
就够了?
我没有使用spring boot
或任何libraries
。
这是我的pom.xml
libraries
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<log4j.version>1.2.17</log4j.version>
<spring.version>4.2.5.RELEASE</spring.version>
<spring.security.version>4.2.5.RELEASE</spring.security.version>
<java.version>1.8</java.version>
<org.jooq.version>3.7.3</org.jooq.version>
<org.h2.version>1.4.181</org.h2.version>
<org.postgresql.version>9.4-1201-jdbc41</org.postgresql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>$org.jooq.version</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>4.0.0.Final</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>$org.h2.version</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>$org.postgresql.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>$spring.version</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>$spring.security.version</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>$spring.security.version</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-root.xml</param-value>
</context-param>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-root.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
和spring-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="ge.economy.law"/>
<context:annotation-config/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="dtSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<!--LAWYERS.MIA.GE-->
<property name="url" value="jdbc:postgresql://localhost:5432/lawyers?currentSchema=public"/>
<!--<property name="url" value="jdbc:postgresql://10.31.16.11:5432/lawyers?currentSchema=public"/>-->
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<bean id="transactionAwareDataSource"
class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg ref="dtSource"/>
</bean>
<bean class="org.jooq.impl.DataSourceConnectionProvider" name="connectionProvider">
<constructor-arg ref="transactionAwareDataSource"/>
</bean>
<bean id="dsl" class="org.jooq.impl.DefaultDSLContext">
<constructor-arg ref="config"/>
</bean>
<bean class="org.jooq.impl.DefaultConfiguration" name="config">
<property name="SQLDialect">
<value type="org.jooq.SQLDialect">POSTGRES</value>
</property>
<property name="connectionProvider" ref="connectionProvider"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean name="fileService" class="ge.economy.law.service.FileService">
<!--<property name="rootDir"-->
<!--value="C:\Program Files\Apache Software Foundation\Apache Tomcat 8.0.27\webapps\ROOT\uploads"/>-->
<!--<property name="rootDir" value="/usr/share/tomcat/webapps/domains/lawyers-test.economy.ge/uploads"/>-->
<property name="rootDir" value="/data"/>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000000"/>
</bean>
</beans>
也许我的配置有任何错误?
【问题讨论】:
根据您提供的sn-ps,您的代码很好。我使用 spring boot、spring security 和 keycloak-spring-boot-starter 获得了运行配置。因此,我认为问题出在其他地方。我认为您的 Java 程序配置错误,根本不受 Spring Security 的保护。您能否添加更多信息:-您是否收到任何 403 或 401 响应? - 你可以在没有授权头的情况下提出请求吗? - 你用的是什么版本的keycloak、spring、spring security? 由于某种原因我无法更新我的问题,我没有使用 spring boot 或任何它的库,只是 spring mvc。这是我的 github 链接 (github.com/uchachaduneli/mia_law),您可以查看我的配置,在web.xml
和 spring-root.xml
我更新了问题
【参考方案1】:
我会把它留在这里以备将来使用。 KeyCloackRestTemplate,获取accessToken他们就是用这样的方法。你可以在 org.keycloak.adapters.springsecurity.client->KeycloakClientRequestFactory.class 中找到它
@Controller
@RequestMapping
public class AuthController
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verify(Principal principal,Model model) throws Exception
KeycloakAuthenticationToken keycloakAuthenticationToken = (KeycloakAuthenticationToken) principal;
String token =keycloakAuthenticationToken.getAccount().getKeycloakSecurityContext().getTokenString();
【讨论】:
以上是关于春季无法获取keycloak授权令牌的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Angular -> Spring Boot Oauth2 -> Keycloak 获取 keycloak 令牌