init project v1.0.0
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-auth-client-spring-boot-starter</artifactId>
|
||||
<description>认证客户端通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-oauth2</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-redis-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-context</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
|
||||
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
|
||||
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Import(DefaultSecurityHandlerConfig.class)
|
||||
public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
|
||||
@Autowired
|
||||
private TokenStore tokenStore;
|
||||
|
||||
@Resource
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Resource
|
||||
private OAuth2WebSecurityExpressionHandler expressionHandler;
|
||||
|
||||
@Resource
|
||||
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
@Override
|
||||
public void configure(ResourceServerSecurityConfigurer resources) {
|
||||
resources.tokenStore(tokenStore)
|
||||
.stateless(true)
|
||||
.authenticationEntryPoint(authenticationEntryPoint)
|
||||
.expressionHandler(expressionHandler)
|
||||
.accessDeniedHandler(oAuth2AccessDeniedHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http)
|
||||
.authorizeRequests()
|
||||
.antMatchers(securityProperties.getIgnore().getUrls()).permitAll()
|
||||
.antMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
.anyRequest();
|
||||
setAuthenticate(authorizedUrl);
|
||||
//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
|
||||
http.headers()
|
||||
.frameOptions()
|
||||
.disable()
|
||||
.and()
|
||||
.csrf().disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* url权限控制,默认是认证就通过,可以重写实现个性化
|
||||
* @param authorizedUrl
|
||||
*/
|
||||
public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
|
||||
return authorizedUrl.authenticated().and();
|
||||
}
|
||||
|
||||
/**
|
||||
* 留给子类重写扩展功能
|
||||
* @param http
|
||||
*/
|
||||
public HttpSecurity setHttp(HttpSecurity http) {
|
||||
return http;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.common.utils.ResponseUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
|
||||
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class DefaultSecurityHandlerConfig {
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 未登录,返回401
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationEntryPoint authenticationEntryPoint() {
|
||||
return (request, response, authException) -> {
|
||||
ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.UNAUTHORIZED.value());
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
|
||||
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
|
||||
expressionHandler.setApplicationContext(applicationContext);
|
||||
return expressionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理spring security oauth 处理失败返回消息格式
|
||||
*/
|
||||
@Bean
|
||||
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
|
||||
return new OAuth2AccessDeniedHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
|
||||
ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.FORBIDDEN.value());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.oauth2.common.store.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* token存储配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class TokenStoreConfig {
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db")
|
||||
@Import(AuthDbTokenStore.class)
|
||||
public class JdbcTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true)
|
||||
@Import(AuthRedisTokenStore.class)
|
||||
public class RedisTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt")
|
||||
@Import(AuthJwtTokenStore.class)
|
||||
public class AuthJwtTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt")
|
||||
@Import(ResJwtTokenStore.class)
|
||||
public class ResJwtTokenConfig {
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.central.oauth2.common.constants;
|
||||
|
||||
/**
|
||||
* 权限常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:05
|
||||
*/
|
||||
public enum AuthoritiesEnum {
|
||||
/**
|
||||
* 管理员
|
||||
*/
|
||||
ADMIN("ROLE_ADMIN"),
|
||||
/**
|
||||
* 普通用户
|
||||
*/
|
||||
USER("ROLE_USER"),
|
||||
/**
|
||||
* 匿名用户
|
||||
*/
|
||||
ANONYMOUS("ROLE_ANONYMOUS");
|
||||
|
||||
private String role;
|
||||
|
||||
AuthoritiesEnum(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 认证配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class AuthProperties {
|
||||
/**
|
||||
* 要认证的url
|
||||
*/
|
||||
private String[] httpUrls = {};
|
||||
|
||||
/**
|
||||
* 是否开启url权限验证
|
||||
*/
|
||||
private boolean urlEnabled = false;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 配置需要放权的url白名单
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class PermitProperties {
|
||||
/**
|
||||
* 监控中心和swagger需要访问的url
|
||||
*/
|
||||
private static final String[] ENDPOINTS = {
|
||||
"/oauth/**",
|
||||
"/actuator/**",
|
||||
"/*/v2/api-docs",
|
||||
"/swagger/api-docs",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/druid/**"
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置不用认证的url
|
||||
*/
|
||||
private String[] httpUrls = {};
|
||||
|
||||
/**
|
||||
* 设置认证后不需要判断具体权限的url,所有登录的人都能访问
|
||||
*/
|
||||
private String[] menusPaths = {};
|
||||
|
||||
public String[] getUrls() {
|
||||
if (httpUrls == null || httpUrls.length == 0) {
|
||||
return ENDPOINTS;
|
||||
}
|
||||
List<String> list = new ArrayList<>();
|
||||
for (String url : ENDPOINTS) {
|
||||
list.add(url);
|
||||
}
|
||||
for (String url : httpUrls) {
|
||||
list.add(url);
|
||||
}
|
||||
return list.toArray(new String[list.size()]);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2019/1/4
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.security")
|
||||
@RefreshScope
|
||||
public class SecurityProperties {
|
||||
private AuthProperties auth = new AuthProperties();
|
||||
|
||||
private PermitProperties ignore = new PermitProperties();
|
||||
|
||||
private ValidateCodeProperties code = new ValidateCodeProperties();
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 验证码配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/4
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class ValidateCodeProperties {
|
||||
/**
|
||||
* 设置认证通时不需要验证码的clientId
|
||||
*/
|
||||
private String[] ignoreClientCode = {};
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.central.oauth2.common.service;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 请求权限判断service
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/28
|
||||
*/
|
||||
public interface IPermissionService {
|
||||
/**
|
||||
* 判断请求是否有权限
|
||||
*
|
||||
* @param authentication 认证信息
|
||||
* @return 是否有权限
|
||||
*/
|
||||
boolean hasPermission(HttpServletRequest request, Authentication authentication);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.central.oauth2.common.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.model.SysMenu;
|
||||
import com.central.common.utils.SysUserUtil;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.service.IPermissionService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 请求权限判断service
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/28
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class DefaultPermissionServiceImpl implements IPermissionService {
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
private AntPathMatcher antPathMatcher = new AntPathMatcher();
|
||||
|
||||
/**
|
||||
* 查询当前用户拥有的资源权限
|
||||
* @param roleCodes 角色code列表,多个以','隔开
|
||||
* @return
|
||||
*/
|
||||
public abstract List<SysMenu> findMenuByRoleCodes(String roleCodes);
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
|
||||
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
|
||||
// 在这里放行具有一定风险,也可通过前端配置代理实现
|
||||
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
|
||||
return true;
|
||||
}
|
||||
boolean hasPermission = false;
|
||||
if (!(authentication instanceof AnonymousAuthenticationToken)) {
|
||||
//判断是否开启url权限验证
|
||||
if (!securityProperties.getAuth().isUrlEnabled()) {
|
||||
return true;
|
||||
}
|
||||
//超级管理员admin不需认证
|
||||
String username = SysUserUtil.getUsername(authentication);
|
||||
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
//判断认证通过后,所以用户都能访问的url
|
||||
for (String path : securityProperties.getIgnore().getMenusPaths()) {
|
||||
if (antPathMatcher.match(path, request.getRequestURI())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
|
||||
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
|
||||
log.warn("角色列表为空:{}", authentication.getPrincipal());
|
||||
return hasPermission;
|
||||
}
|
||||
|
||||
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
|
||||
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
|
||||
for (SysMenu menu : menuList) {
|
||||
if (StringUtils.isNotEmpty(menu.getPath()) && StringUtils.isNotEmpty(menu.getPathMethod())
|
||||
&& antPathMatcher.match(menu.getPath(), request.getRequestURI())
|
||||
&& request.getMethod().equalsIgnoreCase(menu.getPathMethod())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return hasPermission;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 认证服务器使用数据库存取令牌
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:23
|
||||
*/
|
||||
public class AuthDbTokenStore {
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(){
|
||||
return new JdbcTokenStore(dataSource);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.security.KeyPair;
|
||||
|
||||
/**
|
||||
* 认证服务器使用 JWT RSA 非对称加密令牌
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:21
|
||||
*/
|
||||
public class AuthJwtTokenStore {
|
||||
|
||||
@Bean("keyProp")
|
||||
public KeyProperties keyProperties() {
|
||||
return new KeyProperties();
|
||||
}
|
||||
|
||||
@Resource(name = "keyProp")
|
||||
private KeyProperties keyProperties;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
|
||||
return new JwtTokenStore(jwtAccessTokenConverter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAccessTokenConverter jwtAccessTokenConverter() {
|
||||
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
||||
KeyPair keyPair = new KeyStoreKeyFactory
|
||||
(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray())
|
||||
.getKeyPair(keyProperties.getKeyStore().getAlias());
|
||||
converter.setKeyPair(keyPair);
|
||||
return converter;
|
||||
}
|
||||
|
||||
/**
|
||||
* jwt 生成token 定制化处理
|
||||
* 添加一些额外的用户信息到token里面
|
||||
*
|
||||
* @return TokenEnhancer
|
||||
*/
|
||||
/*@Bean
|
||||
public TokenEnhancer tokenEnhancer() {
|
||||
return (accessToken, authentication) -> {
|
||||
final Map<String, Object> additionalInfo = new HashMap<>(1);
|
||||
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
|
||||
return accessToken;
|
||||
};
|
||||
}*/
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
/**
|
||||
* 认证服务器使用Redis存取令牌
|
||||
* 注意: 需要配置redis参数
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/25 9:36
|
||||
*/
|
||||
public class AuthRedisTokenStore {
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate ;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore() {
|
||||
RedisTemplateTokenStore redisTemplateStore = new RedisTemplateTokenStore() ;
|
||||
redisTemplateStore.setRedisTemplate(redisTemplate);
|
||||
return redisTemplateStore;
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
|
||||
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 支持redis cluster模式
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/27 11:33
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedisTemplateTokenStore implements TokenStore {
|
||||
private static final String ACCESS = "access:";
|
||||
private static final String AUTH_TO_ACCESS = "auth_to_access:";
|
||||
private static final String AUTH = "auth:";
|
||||
private static final String REFRESH_AUTH = "refresh_auth:";
|
||||
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
|
||||
private static final String REFRESH = "refresh:";
|
||||
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
|
||||
private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
|
||||
private static final String UNAME_TO_ACCESS = "uname_to_access:";
|
||||
private static final String TOKEN = "token:";
|
||||
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
|
||||
|
||||
public RedisTemplate<String, Object> getRedisTemplate() {
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
|
||||
this.authenticationKeyGenerator = authenticationKeyGenerator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
|
||||
String key = authenticationKeyGenerator.extractKey(authentication);
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) redisTemplate.opsForValue().get(AUTH_TO_ACCESS + key);
|
||||
if (accessToken != null
|
||||
&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
|
||||
storeAccessToken(accessToken, authentication);
|
||||
}
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
|
||||
return readAuthentication(token.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthentication(String token) {
|
||||
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
|
||||
return readAuthenticationForRefreshToken(token.getValue());
|
||||
}
|
||||
|
||||
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
|
||||
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(REFRESH_AUTH + token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
|
||||
OAuth2AccessToken existingAccessToken = this.getAccessToken(authentication);
|
||||
this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token);
|
||||
this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication);
|
||||
this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), token);
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("clientId", authentication.getOAuth2Request().getClientId());
|
||||
|
||||
if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
|
||||
UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication.getUserAuthentication();
|
||||
LoginAppUser appUser = (LoginAppUser) authenticationToken.getPrincipal();
|
||||
params.put("username", appUser.getUsername());
|
||||
params.put("authorities", appUser.getAuthorities());
|
||||
}
|
||||
if (!params.isEmpty()) {
|
||||
this.redisTemplate.opsForValue().set(TOKEN + token.getValue(), params);
|
||||
}
|
||||
if (!authentication.isClientOnly()) {
|
||||
if (existingAccessToken != null) {
|
||||
if (!existingAccessToken.isExpired()) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(UNAME_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
|
||||
}
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
|
||||
}
|
||||
}
|
||||
|
||||
if (existingAccessToken != null) {
|
||||
if (!existingAccessToken.isExpired()) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);
|
||||
}
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);
|
||||
}
|
||||
|
||||
if (token.getExpiration() != null) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
OAuth2RefreshToken refreshToken = token.getRefreshToken();
|
||||
if (refreshToken != null && refreshToken.getValue() != null) {
|
||||
this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), token.getValue());
|
||||
this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), token.getRefreshToken().getValue());
|
||||
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
|
||||
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
|
||||
Date expiration = expiringRefreshToken.getExpiration();
|
||||
if (expiration != null) {
|
||||
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
|
||||
|
||||
redisTemplate.expire(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(ACCESS_TO_REFRESH + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getApprovalKey(OAuth2Authentication authentication) {
|
||||
String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication().getName();
|
||||
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
|
||||
}
|
||||
|
||||
private String getApprovalKey(String clientId, String userName) {
|
||||
return clientId + (userName == null ? "" : ":" + userName);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void removeAccessToken(OAuth2AccessToken accessToken) {
|
||||
removeAccessToken(accessToken.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AccessToken readAccessToken(String tokenValue) {
|
||||
return (OAuth2AccessToken) this.redisTemplate.opsForValue().get(ACCESS + tokenValue);
|
||||
}
|
||||
|
||||
public void removeAccessToken(String tokenValue) {
|
||||
OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + tokenValue);
|
||||
this.redisTemplate.delete(AUTH + tokenValue);
|
||||
redisTemplate.delete(ACCESS + tokenValue);
|
||||
redisTemplate.delete(TOKEN + tokenValue);
|
||||
this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue);
|
||||
if (authentication != null) {
|
||||
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
|
||||
String clientId = authentication.getOAuth2Request().getClientId();
|
||||
redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName()));
|
||||
redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId);
|
||||
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
|
||||
this.redisTemplate.opsForValue().set(REFRESH + refreshToken.getValue(), refreshToken);
|
||||
this.redisTemplate.opsForValue().set(REFRESH_AUTH + refreshToken.getValue(), authentication);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
|
||||
return (OAuth2RefreshToken) this.redisTemplate.opsForValue().get(REFRESH + tokenValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
|
||||
removeRefreshToken(refreshToken.getValue());
|
||||
}
|
||||
|
||||
public void removeRefreshToken(String tokenValue) {
|
||||
this.redisTemplate.delete(REFRESH + tokenValue);
|
||||
this.redisTemplate.delete(REFRESH_AUTH + tokenValue);
|
||||
this.redisTemplate.delete(REFRESH_TO_ACCESS + tokenValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
|
||||
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
|
||||
}
|
||||
|
||||
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
|
||||
String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken);
|
||||
if (token != null) {
|
||||
redisTemplate.delete(REFRESH_TO_ACCESS + refreshToken);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
|
||||
List<Object> result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, -1);
|
||||
if (result == null || result.size() == 0) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
|
||||
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
|
||||
accessTokens.add(accessToken);
|
||||
}
|
||||
return Collections.unmodifiableCollection(accessTokens);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
|
||||
List<Object> result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1);
|
||||
if (result == null || result.size() == 0) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
|
||||
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
|
||||
accessTokens.add(accessToken);
|
||||
}
|
||||
return Collections.unmodifiableCollection(accessTokens);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/8/20 9:25
|
||||
*/
|
||||
public class ResJwtTokenStore {
|
||||
private static final String PUBLIC_KEY = "pubkey.txt";
|
||||
|
||||
@Autowired
|
||||
private ResourceServerProperties resource;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
|
||||
return new JwtTokenStore(jwtAccessTokenConverter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAccessTokenConverter jwtAccessTokenConverter() {
|
||||
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
||||
converter.setVerifierKey(getPubKey());
|
||||
return converter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取非对称加密公钥 Key
|
||||
* @return 公钥 Key
|
||||
*/
|
||||
private String getPubKey() {
|
||||
Resource resource = new ClassPathResource(ResJwtTokenStore.PUBLIC_KEY);
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
|
||||
return br.lines().collect(Collectors.joining("\n"));
|
||||
} catch (IOException ioe) {
|
||||
return getKeyFromAuthorizationServer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过访问授权服务器获取非对称加密公钥 Key
|
||||
* @return 公钥 Key
|
||||
*/
|
||||
private String getKeyFromAuthorizationServer() {
|
||||
if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) {
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
final String username = this.resource.getClientId();
|
||||
final String password = this.resource.getClientSecret();
|
||||
if (username != null && password != null) {
|
||||
final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes());
|
||||
headers.add("Authorization", "Basic " + new String(token));
|
||||
}
|
||||
final HttpEntity<Void> request = new HttpEntity<>(headers);
|
||||
final String url = this.resource.getJwt().getKeyUri();
|
||||
return (String) new RestTemplate()
|
||||
.exchange(url, HttpMethod.GET, request, Map.class).getBody()
|
||||
.get("value");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.central.oauth2.common.util;
|
||||
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.Enumeration;
|
||||
|
||||
/**
|
||||
* 认证授权相关工具类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/13
|
||||
*/
|
||||
@Slf4j
|
||||
public class AuthUtils {
|
||||
private static final String BASIC_ = "Basic ";
|
||||
|
||||
/**
|
||||
* 获取requet(head/param)中的token
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String extractToken(HttpServletRequest request) {
|
||||
String token = extractHeaderToken(request);
|
||||
if (token == null) {
|
||||
token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
|
||||
if (token == null) {
|
||||
log.debug("Token not found in request parameters. Not an OAuth2 request.");
|
||||
}
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析head中的token
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private static String extractHeaderToken(HttpServletRequest request) {
|
||||
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
|
||||
while (headers.hasMoreElements()) {
|
||||
String value = headers.nextElement();
|
||||
if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
|
||||
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
|
||||
int commaIndex = authHeaderValue.indexOf(',');
|
||||
if (commaIndex > 0) {
|
||||
authHeaderValue = authHeaderValue.substring(0, commaIndex);
|
||||
}
|
||||
return authHeaderValue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* *从header 请求中的clientId:clientSecret
|
||||
*/
|
||||
public static String[] extractClient(HttpServletRequest request) throws IOException, UnapprovedClientAuthenticationException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith(BASIC_)) {
|
||||
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
|
||||
}
|
||||
return extractHeaderClient(header);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从header 请求中的clientId:clientSecret
|
||||
*
|
||||
* @param header header中的参数
|
||||
*/
|
||||
public static String[] extractHeaderClient(String header) throws IOException {
|
||||
byte[] base64Client = header.substring(BASIC_.length()).getBytes(CommonConstant.UTF8);
|
||||
byte[] decoded = Base64.getDecoder().decode(base64Client);
|
||||
String clientStr = new String(decoded, CommonConstant.UTF8);
|
||||
String[] clientArr = clientStr.split(":");
|
||||
if (clientArr.length != 2) {
|
||||
throw new RuntimeException("Invalid basic authentication token");
|
||||
}
|
||||
return clientArr;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user