最近团队的各项目接入keycloak统一管理用户的登录认证,鉴权由各项目独立实现
1、在keycloak中配置client
keycloak管理界面点击client,创建client,填写clientID
有效的重定向URI配置指向工单系统的UI首页地址
启用隐式流
web起源设为 *
2、加入keycloak依赖和json文件
pom.xml
<!-- KeyCloak -->
<keycloak.version>4.4.0.Final</keycloak.version>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>${keycloak.version}</version>
</dependency>
keycloak.json文件,放在resources目录下
{
"realm": "realm",
"auth-server-url": "http://xxx.xxx:8180/auth",
"ssl-required": "external",
"resource": "myclient",
"public-client": true,
"confidential-port": 0
}
application.properties文件
#keycloak
keycloak.realm=realm
keycloak.resource=myclient
keycloak.auth-server-url=http://xxx.xxx.xxx.xxx:8180/auth
keycloak.ssl-required=external
3、添加springsecurity+keycloak配置文件
不废话,直接上代码
@KeycloakConfiguration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
private SecurityAuthenticationProvider authenticationProvider;
@Autowired
private KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter;
@Autowired
private KeycloakPreAuthActionsFilter keycloakPreAuthActionsFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Bean
public KeycloakConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
KeycloakAuthenticationProcessingFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(true);
return registrationBean;
}
@Bean
public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
KeycloakPreAuthActionsFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(true);
return registrationBean;
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().and()
.sessionManagement().disable()
.authorizeRequests()
.anyRequest().permitAll();
http
//.addFilterBefore(mySecurityInterceptor, FilterSecurityInterceptor.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter, FilterSecurityInterceptor.class)
.addFilterBefore(keycloakPreAuthActionsFilter, KeycloakAuthenticationProcessingFilter.class);
}
}
4、自定义AuthenticationProvider
通过AccessToken中的用户信息,查询本系统中该用户的权限信息,加入token,具体鉴权方案各系统各不相同,自行实现
@Slf4j
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
private GrantedAuthoritiesMapper grantedAuthoritiesMapper;
public void setGrantedAuthoritiesMapper(GrantedAuthoritiesMapper grantedAuthoritiesMapper) {
this.grantedAuthoritiesMapper = grantedAuthoritiesMapper;
}
/**
* 验证Authentication,建立系统使用者信息principal(token)
*/
@Override
public Authentication authenticate(Authentication authentication) throws RuntimeException {
//从token中获取用户信息
KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication;
AccessToken accessToken = getAccessToken((token));
String userId = accessToken.getSubject();
//查询用户是否存在,若不存在则存入数据库
userService.checkUser(accessToken, userId);
//根据userId查询本系统用户权限,放入token中
List<GrantedAuthority> grantedAuthorities = roleService.getGrantedAuthorities(userId);
KeycloakAuthenticationToken authenticationToken = new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), mapAuthorities(grantedAuthorities));
return authenticationToken;
}
private AccessToken getAccessToken(KeycloakAuthenticationToken principal) {
KeycloakAuthenticationToken token = principal;
KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal)token.getPrincipal();
KeycloakSecurityContext context = keycloakPrincipal.getKeycloakSecurityContext();
return context.getToken();
}
private Collection<? extends GrantedAuthority> mapAuthorities(
Collection<? extends GrantedAuthority> authorities) {
return grantedAuthoritiesMapper != null
? grantedAuthoritiesMapper.mapAuthorities(authorities)
: authorities;
}
@Override
public boolean supports(Class<?> aClass) {
return KeycloakAuthenticationToken.class.isAssignableFrom(aClass);
}
}