feat: uaa改造为Spring Authorization Server

This commit is contained in:
zlt2000
2023-12-12 10:48:32 +08:00
parent 671ab86543
commit 2a05c6ab91
81 changed files with 2917 additions and 520 deletions
@@ -1,12 +0,0 @@
package com.central.file.config;
import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -1,11 +0,0 @@
package com.central.common.config;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -1,12 +0,0 @@
package com.central.user.config;
import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zlt
* @date 2019/8/5
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -3,10 +3,8 @@ package com.central.user.controller;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.*;
@@ -165,12 +163,9 @@ public class SysMenuController {
*/
@GetMapping("/current")
@Operation(summary = "查询当前用户菜单")
public List<SysMenu> findMyMenu(@LoginUser SysUser user) {
List<SysRole> roles = user.getRoles();
if (CollectionUtil.isEmpty(roles)) {
return Collections.emptyList();
}
List<SysMenu> menus = menuService.findByRoleCodes(roles.stream().map(SysRole::getCode).collect(Collectors.toSet()), CommonConstant.MENU);
public List<SysMenu> findMyMenu() {
LoginAppUser user = LoginUserContextHolder.getUser();
List<SysMenu> menus = menuService.findByUserId(user.getId(), CommonConstant.MENU);
return treeBuilder(menus);
}
}
@@ -8,10 +8,10 @@ import java.util.Set;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.CommonConstant;
import com.central.common.model.*;
import com.central.common.utils.ExcelUtil;
import com.central.common.utils.LoginUserUtils;
import com.central.log.annotation.AuditLog;
import com.central.search.client.service.IQueryService;
import com.central.search.model.LogicDelDto;
@@ -65,8 +65,8 @@ public class SysUserController {
*/
@Operation(summary = "根据access_token当前登录用户")
@GetMapping("/users/current")
public Result<LoginAppUser> getLoginAppUser(@LoginUser(isFull = true) SysUser user) {
return Result.succeed(appUserService.getLoginAppUser(user));
public Result<LoginAppUser> getLoginAppUser() {
return Result.succeed(LoginUserUtils.getCurrentUser(true));
}
/**
@@ -84,7 +84,7 @@ public class SysUserController {
*/
@GetMapping(value = "/users-anon/login", params = "username")
@Operation(summary = "根据用户名查询用户")
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
return appUserService.findByUsername(username);
}
@@ -95,7 +95,7 @@ public class SysUserController {
*/
@GetMapping(value = "/users-anon/mobile", params = "mobile")
@Operation(summary = "根据手机号查询用户")
public LoginAppUser findByMobile(String mobile) {
public SysUser findByMobile(String mobile) {
return appUserService.findByMobile(mobile);
}
@@ -106,7 +106,7 @@ public class SysUserController {
*/
@GetMapping(value = "/users-anon/openId", params = "openId")
@Operation(summary = "根据OpenId查询用户")
public LoginAppUser findByOpenId(String openId) {
public SysUser findByOpenId(String openId) {
return appUserService.findByOpenId(openId);
}
@@ -3,6 +3,9 @@ package com.central.user.mapper;
import com.central.db.mapper.SuperMapper;
import com.central.common.model.SysMenu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 菜单
@@ -11,5 +14,5 @@ import org.apache.ibatis.annotations.Mapper;
*/
@Mapper
public interface SysMenuMapper extends SuperMapper<SysMenu> {
List<SysMenu> findByUserId(@Param("userId") Long userId, @Param("type") Integer type);
}
@@ -34,6 +34,8 @@ public interface ISysMenuService extends ISuperService<SysMenu> {
*/
List<SysMenu> findByRoles(Set<Long> roleIds);
List<SysMenu> findByUserId(Long userId, Integer type);
/**
* 角色菜单列表
* @param roleIds 角色ids
@@ -8,7 +8,6 @@ import com.central.common.service.ISuperService;
import com.central.user.model.SysUserExcel;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
@@ -24,18 +23,18 @@ public interface ISysUserService extends ISuperService<SysUser> {
* @param username
* @return
*/
LoginAppUser findByUsername(String username);
SysUser findByUsername(String username);
LoginAppUser findByOpenId(String username);
SysUser findByOpenId(String username);
LoginAppUser findByMobile(String username);
SysUser findByMobile(String username);
/**
* 通过SysUser 转换为 LoginAppUser,把roles和permissions也查询出来
* 通过SysUser 把roles和permissions也查询出来
* @param sysUser
* @return
*/
LoginAppUser getLoginAppUser(SysUser sysUser);
void setUserPermission(SysUser sysUser);
/**
* 根据用户名查询用户
@@ -66,6 +66,10 @@ public class SysMenuServiceImpl extends SuperServiceImpl<SysMenuMapper, SysMenu>
public List<SysMenu> findByRoleCodes(Set<String> roleCodes, Integer type) {
return roleMenuService.findMenusByRoleCodes(roleCodes, type);
}
@Override
public List<SysMenu> findByUserId(Long userId, Integer type) {
return baseMapper.findByUserId(userId, type);
}
/**
* 查询所有菜单
@@ -21,8 +21,6 @@ import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -55,48 +53,43 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
private DistributedLock lock;
@Override
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
SysUser sysUser = this.selectByUsername(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser findByOpenId(String username) {
public SysUser findByOpenId(String username) {
SysUser sysUser = this.selectByOpenId(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser findByMobile(String username) {
public SysUser findByMobile(String username) {
SysUser sysUser = this.selectByMobile(username);
return getLoginAppUser(sysUser);
setUserPermission(sysUser);
return sysUser;
}
@Override
public LoginAppUser getLoginAppUser(SysUser sysUser) {
public void setUserPermission(SysUser sysUser) {
if (sysUser != null) {
List<SysRole> sysRoles = roleUserService.findRolesByUserId(sysUser.getId());
Collection<GrantedAuthority> authorities = new HashSet<>();
if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
}
sysUser.setRoles(sysRoles);
Set<String> permissions = null;
Set<String> permissions;
if (!CollectionUtils.isEmpty(sysRoles)) {
Set<Long> roleIds = sysRoles.stream().map(SuperEntity::getId).collect(Collectors.toSet());
List<SysMenu> menus = roleMenuMapper.findMenusByRoleIds(roleIds, CommonConstant.PERMISSION);
if (!CollectionUtils.isEmpty(menus)) {
permissions = menus.stream().map(p -> p.getPath())
.collect(Collectors.toSet());
sysUser.setPermissions(permissions);
}
}
return new LoginAppUser(sysUser.getId()
, sysUser.getUsername(), sysUser.getPassword()
, sysUser.getMobile(), permissions
, sysUser.getEnabled(), true, true, true
, authorities);
}
return null;
}
/**
@@ -2,5 +2,15 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.user.mapper.SysMenuMapper">
<select id="findByUserId" resultType="com.central.common.model.SysMenu">
select distinct t.* from sys_menu t
inner join sys_role_menu r on r.menu_id = t.id
inner join sys_role_user ru on ru.role_id = r.role_id
where ru.user_id = #{userId}
<if test="type != null">
and t.type = #{type}
</if>
and t.hidden = 0
ORDER BY sort ASC
</select>
</mapper>
@@ -1,6 +1,5 @@
package com.central.user.service;
import com.central.common.model.LoginAppUser;
import static org.assertj.core.api.Assertions.*;
import com.central.common.model.PageResult;
@@ -27,8 +26,8 @@ public class SysUserServiceTest {
@Test
public void testFindByUsername() {
LoginAppUser loginAppUser = sysUserService.findByUsername("admin");
assertThat(loginAppUser).isNotNull();
SysUser sysUser = sysUserService.findByUsername("admin");
assertThat(sysUser).isNotNull();
}
@Test
@@ -56,6 +56,7 @@ public class DefaultResourceServerConf {
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
).csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
@@ -0,0 +1,17 @@
package com.central.oauth2.common.exception;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* @author: zlt
* @date: 2023/12/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomOAuth2AuthorizationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthorizationException(String msg) {
super(new OAuth2Error(msg), msg);
}
}
@@ -35,14 +35,11 @@ public class ClientDto implements Serializable {
private Integer refreshTokenValiditySeconds = 28800;
private String additionalInformation = "{}";
private String autoapprove = "true";
/**
* 是否支持id_token
* token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
*/
private Boolean supportIdToken = true;
/**
* id_token有效时间(s)
*/
private Integer idTokenValiditySeconds = 60;
private String tokenFormat = "reference";
private Long creatorId;
}
@@ -1,5 +1,6 @@
package com.central.oauth2.common.properties;
import com.central.common.constant.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
@@ -23,11 +24,11 @@ public class PermitProperties {
* 监控中心和swagger需要访问的url
*/
private static final String[] ENDPOINTS = {
"/login.html", "/validata/code/**",
"/v3/api-docs/**", "/*/v3/api-docs/**",
"/doc.html", "/swagger-ui.html", "/swagger-ui/**",
SecurityConstants.LOGIN_PAGE,
SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/**",
"/doc.html", "/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**",
"/actuator/**", "/webjars/**", "/druid/**",
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error",
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error"
};
/**
@@ -6,6 +6,7 @@ import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.token.CustomAccessToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.ExpiredObjectListener;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
@@ -28,6 +29,11 @@ import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* 实现 Redis 存储 OAuth2Authorization 对象
* 1. 自动续签token(可配置是否开启)
* 2. 增加 client_id_to_access 和 uname_to_access 两个集合,用于查看在线用户
* 3. 增加过期监听,删除 client_id_to_access 和 uname_to_access 集合的值
*
* @author: zlt
* @date: 2023/11/9
* <p>
@@ -38,7 +44,7 @@ import java.util.*;
@RequiredArgsConstructor
public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private final static Long TIMEOUT = 10L;
private final static Long STATE_TIMEOUT_MINUTES = 10L;
private static final String AUTHORIZATION = "token";
@@ -46,11 +52,32 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
private final RedissonClient redisson;
private final ExpiredObjectListener expiredObjectListener = new ExpiredObjectListener() {
private final static String KEY_SPLIT = "::";
/**
* redis 失效监听,删除集合里的值
* 在 redis.conf 文件中,确保以下设置是启用的:notify-keyspace-events Ex
* 监听的key格式为:token::access_token::${clientId}::${username}::${access_token}
* 例如:token::access_token::webApp::admin::q7ySjsjZoinAx0zUJADqV9P1VmCwYmQDdemwOuhDHjNXVmkzkvquMk_vUBX_Yz40JModOhUwixu-ICH5hti50-KXngBgkn_V1pxu-PZ1YGNkBIDXneE0z4WYx6uFIVHS
*/
@Override
public void onExpired(String name) {
String[] keyArr = name.split(KEY_SPLIT);
if (keyArr.length == 5) {
String clientId = keyArr[2];
String username = keyArr[3];
String accessToken = keyArr[4];
redisListDelete(getClientIdListKey(clientId), accessToken);
redisListDelete(getUnameListKey(clientId, username), accessToken);
}
}
};
@Override
public void save(OAuth2Authorization authorization) {
if (isState(authorization)) {
String token = authorization.getAttribute("state");
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(TIMEOUT));
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(STATE_TIMEOUT_MINUTES));
}
if (isCode(authorization)) {
@@ -76,9 +103,22 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
}
private Duration saveAccessToken(OAuth2Authorization authorization) {
return this.saveAccessToken(authorization, false);
}
private Duration saveAccessToken(OAuth2Authorization authorization, boolean isRenew) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
Duration duration = this.getExpireSeconds(accessToken);
this.redisBucketSet(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue(), authorization, duration);
RBucket<Integer> listenKeyBucket = redisson.getBucket(buildListenerKey(
OAuth2ParameterNames.ACCESS_TOKEN, authorization.getRegisteredClientId()
, authorization.getPrincipalName(), accessToken.getTokenValue()));
if (!isRenew) {
listenKeyBucket.set(1, duration);
listenKeyBucket.addListener(expiredObjectListener);
} else {
listenKeyBucket.expire(duration);
}
return duration;
}
@@ -94,7 +134,7 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
}
@@ -154,13 +194,17 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
private String buildListenerKey(String type, String clientId, String username, String tokenValue) {
return String.format("%s::%s::%s::%s::%s", AUTHORIZATION, type, clientId, username, tokenValue);
}
private static boolean isState(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAttribute("state"));
}
private static boolean isCode(OAuth2Authorization authorization) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
.getToken(OAuth2AuthorizationCode.class);
return Objects.nonNull(authorizationCode);
}
@@ -228,10 +272,6 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
/**
* 更新 access_token 的过期时间
*/
@@ -247,7 +287,7 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>> newTokens = new HashMap<>(tokens);
newTokens.put(OAuth2AccessToken.class, newToken);
tokensField.set(authorization, Collections.unmodifiableMap(newTokens));
this.saveAccessToken(authorization);
this.saveAccessToken(authorization, true);
// 更新集合中的过期时间
this.updateListExpiresAt(this.getClientIdListKey(authorization), Duration.ofSeconds(validitySeconds));
this.updateListExpiresAt(this.getUnameListKey(authorization), Duration.ofSeconds(validitySeconds));
@@ -286,7 +326,6 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
private RBucket<OAuth2Authorization> redisBucketSet(String type, String id, OAuth2Authorization value, Duration duration) {
RBucket<OAuth2Authorization> rBucket = redisson.getBucket(buildKey(type, id), AUTH_CODEC);
rBucket.set(value, duration);
return rBucket;
}
@@ -319,4 +358,8 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
rList.remove(value);
return rList;
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
@@ -0,0 +1,36 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author: zlt
* @date: 2023/11/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class MobileAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("mobile_password");
private final Object principal;
private final String credentials;
public MobileAuthenticationToken(String mobile, String password) {
super(GRANT_TYPE);
this.principal = mobile;
this.credentials = password;
super.setAuthenticated(true);
}
public MobileAuthenticationToken(UserDetails user, String password, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
}
}
@@ -0,0 +1,32 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class OpenIdAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("openId");
private final Object principal;
public OpenIdAuthenticationToken(String openId) {
super(GRANT_TYPE);
this.principal = openId;
super.setAuthenticated(true);
}
public OpenIdAuthenticationToken(UserDetails principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
}
}
@@ -0,0 +1,42 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class PasswordCodeAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password_code");
private final Object principal;
private final String credentials;
private final String deviceId;
private final String validCode;
public PasswordCodeAuthenticationToken(String username, String password, String deviceId, String validCode) {
super(GRANT_TYPE);
this.principal = username;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = validCode;
super.setAuthenticated(true);
}
public PasswordCodeAuthenticationToken(UserDetails user, String password, String deviceId
, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = null;
}
}
@@ -5,7 +5,7 @@ import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.LoginAppUser;
import com.central.common.utils.LoginUserUtils;
import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.exception.CustomOAuth2AuthorizationException;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
@@ -115,7 +115,7 @@ public class AuthUtils {
public static String[] extractClient(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthenticationException("The client information in the request header is empty");
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
return extractHeaderClient(header);
}
@@ -123,7 +123,7 @@ public class AuthUtils {
public static String extractClientId(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthenticationException("The client information in the request header is empty");
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
String[] clientArr = extractHeaderClient(header);
return clientArr[0];
@@ -140,7 +140,7 @@ public class AuthUtils {
String clientStr = new String(decoded, StandardCharsets.UTF_8);
String[] clientArr = clientStr.split(":");
if (clientArr.length != 2) {
throw new CustomOAuth2AuthenticationException("Invalid basic authentication token");
throw new CustomOAuth2AuthorizationException("Invalid basic authentication token");
}
return clientArr;
}
@@ -0,0 +1,197 @@
package com.central.oauth2.common.util;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OAuth2ConfigurerUtils {
private OAuth2ConfigurerUtils() {
}
public static RegisteredClientRepository getRegisteredClientRepository(HttpSecurity httpSecurity) {
RegisteredClientRepository registeredClientRepository = httpSecurity.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) {
registeredClientRepository = getBean(httpSecurity, RegisteredClientRepository.class);
httpSecurity.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
}
return registeredClientRepository;
}
public static OAuth2AuthorizationService getAuthorizationService(HttpSecurity httpSecurity) {
OAuth2AuthorizationService authorizationService = httpSecurity.getSharedObject(OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = getOptionalBean(httpSecurity, OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = new InMemoryOAuth2AuthorizationService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationService.class, authorizationService);
}
return authorizationService;
}
public static OAuth2AuthorizationConsentService getAuthorizationConsentService(HttpSecurity httpSecurity) {
OAuth2AuthorizationConsentService authorizationConsentService = httpSecurity.getSharedObject(OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = getOptionalBean(httpSecurity, OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = new InMemoryOAuth2AuthorizationConsentService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationConsentService.class, authorizationConsentService);
}
return authorizationConsentService;
}
@SuppressWarnings("unchecked")
public static OAuth2TokenGenerator<? extends OAuth2Token> getTokenGenerator(HttpSecurity httpSecurity) {
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = httpSecurity.getSharedObject(OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
tokenGenerator = getOptionalBean(httpSecurity, OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
JwtGenerator jwtGenerator = getJwtGenerator(httpSecurity);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer = getAccessTokenCustomizer(httpSecurity);
if (accessTokenCustomizer != null) {
accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer);
}
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
if (jwtGenerator != null) {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
} else {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
accessTokenGenerator, refreshTokenGenerator);
}
}
httpSecurity.setSharedObject(OAuth2TokenGenerator.class, tokenGenerator);
}
return tokenGenerator;
}
private static JwtGenerator getJwtGenerator(HttpSecurity httpSecurity) {
JwtGenerator jwtGenerator = httpSecurity.getSharedObject(JwtGenerator.class);
if (jwtGenerator == null) {
JwtEncoder jwtEncoder = getJwtEncoder(httpSecurity);
if (jwtEncoder != null) {
jwtGenerator = new JwtGenerator(jwtEncoder);
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = getJwtCustomizer(httpSecurity);
if (jwtCustomizer != null) {
jwtGenerator.setJwtCustomizer(jwtCustomizer);
}
httpSecurity.setSharedObject(JwtGenerator.class, jwtGenerator);
}
}
return jwtGenerator;
}
private static JwtEncoder getJwtEncoder(HttpSecurity httpSecurity) {
JwtEncoder jwtEncoder = httpSecurity.getSharedObject(JwtEncoder.class);
if (jwtEncoder == null) {
jwtEncoder = getOptionalBean(httpSecurity, JwtEncoder.class);
if (jwtEncoder == null) {
JWKSource<SecurityContext> jwkSource = getJwkSource(httpSecurity);
if (jwkSource != null) {
jwtEncoder = new NimbusJwtEncoder(jwkSource);
}
}
if (jwtEncoder != null) {
httpSecurity.setSharedObject(JwtEncoder.class, jwtEncoder);
}
}
return jwtEncoder;
}
@SuppressWarnings("unchecked")
public static JWKSource<SecurityContext> getJwkSource(HttpSecurity httpSecurity) {
JWKSource<SecurityContext> jwkSource = httpSecurity.getSharedObject(JWKSource.class);
if (jwkSource == null) {
ResolvableType type = ResolvableType.forClassWithGenerics(JWKSource.class, SecurityContext.class);
jwkSource = getOptionalBean(httpSecurity, type);
if (jwkSource != null) {
httpSecurity.setSharedObject(JWKSource.class, jwkSource);
}
}
return jwkSource;
}
private static OAuth2TokenCustomizer<JwtEncodingContext> getJwtCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
return getOptionalBean(httpSecurity, type);
}
private static OAuth2TokenCustomizer<OAuth2TokenClaimsContext> getAccessTokenCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, OAuth2TokenClaimsContext.class);
return getOptionalBean(httpSecurity, type);
}
public static AuthorizationServerSettings getAuthorizationServerSettings(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = httpSecurity.getSharedObject(AuthorizationServerSettings.class);
if (authorizationServerSettings == null) {
authorizationServerSettings = getBean(httpSecurity, AuthorizationServerSettings.class);
httpSecurity.setSharedObject(AuthorizationServerSettings.class, authorizationServerSettings);
}
return authorizationServerSettings;
}
public static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
}
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
public static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
httpSecurity.getSharedObject(ApplicationContext.class), type);
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " +
beansMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
public static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return names.length == 1 ? (T) context.getBean(names[0]) : null;
}
}
+6 -5
View File
@@ -14,13 +14,10 @@
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
@@ -101,5 +98,9 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
@@ -1,16 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数上添加该注解,则注入当前登录账号的应用id
* 例:public void test(@LoginClient String clientId) //注入webApp
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginClient {
}
@@ -1,21 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数SysUser上添加该注解,则注入当前登录人信息
* 例1:public void test(@LoginUser SysUser user) //只有username 和 roles
* 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginUser {
/**
* 是否查询SysUser对象所有信息,true则通过rpc接口查询
*/
boolean isFull() default false;
}
@@ -1,39 +0,0 @@
package com.central.common.config;
import com.central.common.feign.UserService;
import com.central.common.resolver.ClientArgumentResolver;
import com.central.common.resolver.TokenArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* 默认SpringMVC拦截器
*
* @author zlt
* @date 2019/8/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class DefaultWebMvcConfig implements WebMvcConfigurer {
@Lazy
@Autowired
private UserService userService;
/**
* Token参数解析
*
* @param argumentResolvers 解析类
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//注入用户信息
argumentResolvers.add(new TokenArgumentResolver(userService));
//注入应用信息
argumentResolvers.add(new ClientArgumentResolver());
}
}
@@ -9,6 +9,8 @@ package com.central.common.constant;
* Github: https://github.com/zlt2000
*/
public interface SecurityConstants {
String PROJECT_LICENSE= "http://zlt2000.gitee.io/";
/**
* 用户信息分隔符
*/
@@ -64,6 +66,8 @@ public interface SecurityConstants {
*/
String OAUTH_TOKEN_URL = "/oauth/token";
String OAUTH_CHECK_TOKEN_URL = "/oauth/check_token";
/**
* 默认的处理验证码的url前缀
*/
@@ -161,11 +165,11 @@ public interface SecurityConstants {
/**
* redis中应用对应的token集合的key
*/
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:";
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access";
/**
* redis中用户名对应的token集合的key
*/
String REDIS_UNAME_TO_ACCESS = "uname_to_access:";
String REDIS_UNAME_TO_ACCESS = "uname_to_access";
/**
* rsa公钥
*/
@@ -2,7 +2,6 @@ package com.central.common.feign;
import com.central.common.constant.ServiceNameConstants;
import com.central.common.feign.fallback.UserServiceFallbackFactory;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FeignClient;
@@ -34,7 +33,7 @@ public interface UserService {
* @return
*/
@GetMapping(value = "/users-anon/login", params = "username")
LoginAppUser findByUsername(@RequestParam("username") String username);
SysUser findByUsername(@RequestParam("username") String username);
/**
* 通过手机号查询用户、角色信息
@@ -42,7 +41,7 @@ public interface UserService {
* @param mobile 手机号
*/
@GetMapping(value = "/users-anon/mobile", params = "mobile")
LoginAppUser findByMobile(@RequestParam("mobile") String mobile);
SysUser findByMobile(@RequestParam("mobile") String mobile);
/**
* 根据OpenId查询用户信息
@@ -50,7 +49,7 @@ public interface UserService {
* @param openId openId
*/
@GetMapping(value = "/users-anon/openId", params = "openId")
LoginAppUser findByOpenId(@RequestParam("openId") String openId);
SysUser findByOpenId(@RequestParam("openId") String openId);
/**
@@ -1,7 +1,6 @@
package com.central.common.feign.fallback;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FallbackFactory;
@@ -28,21 +27,21 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
}
@Override
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByMobile(String mobile) {
public SysUser findByMobile(String mobile) {
log.error("通过手机号查询用户异常:{}", mobile, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByOpenId(String openId) {
public SysUser findByOpenId(String openId) {
log.error("通过openId查询用户异常:{}", openId, throwable);
return new LoginAppUser();
return new SysUser();
}
/**
@@ -1,6 +1,7 @@
package com.central.common.model;
import java.util.List;
import java.util.Set;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
@@ -39,4 +40,6 @@ public class SysUser extends SuperEntity {
private String oldPassword;
@TableField(exist = false)
private String newPassword;
@TableField(exist = false)
private Set<String> permissions;
}
@@ -1,53 +0,0 @@
package com.central.common.resolver;
import cn.hutool.core.util.StrUtil;
import com.central.common.annotation.LoginClient;
import com.central.common.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import jakarta.servlet.http.HttpServletRequest;
/**
* head中的应用参数注入clientId中
*
* @author zlt
* @date 2019/7/10
*/
@Slf4j
public class ClientArgumentResolver implements HandlerMethodArgumentResolver {
/**
* 入参筛选
*
* @param methodParameter 参数集合
* @return 格式化后的参数
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(LoginClient.class) && methodParameter.getParameterType().equals(String.class);
}
/**
* @param methodParameter 入参集合
* @param modelAndViewContainer model 和 view
* @param nativeWebRequest web相关
* @param webDataBinderFactory 入参解析
* @return 包装对象
*/
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
String clientId = request.getHeader(SecurityConstants.TENANT_HEADER);
if (StrUtil.isBlank(clientId)) {
log.warn("resolveArgument error clientId is empty");
}
return clientId;
}
}
@@ -1,64 +0,0 @@
package com.central.common.resolver;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Token转化SysUser
*
* @author zlt
* @date 2018/12/21
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
private UserService userService;
public TokenArgumentResolver(UserService userService) {
this.userService = userService;
}
/**
* 入参筛选
*
* @param methodParameter 参数集合
* @return 格式化后的参数
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(SysUser.class);
}
/**
* @param methodParameter 入参集合
* @param modelAndViewContainer model 和 view
* @param nativeWebRequest web相关
* @param webDataBinderFactory 入参解析
* @return 包装对象
*/
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) {
LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
boolean isFull = loginUser.isFull();
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//账号类型
String accountType = request.getHeader(SecurityConstants.ACCOUNT_TYPE_HEADER);
return LoginUserUtils.getCurrentUser(request, isFull);
}
}
@@ -6,6 +6,8 @@ import com.central.common.constant.SecurityConstants;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
@@ -49,7 +51,10 @@ public class LoginUserUtils {
if (StrUtil.isAllNotBlank(username, userId)) {
if (isFull) {
UserService userService = SpringUtil.getBean(UserService.class);
user = userService.findByUsername(username);
SysUser sysUser = userService.findByUsername(username);
if (sysUser != null) {
return getLoginAppUser(sysUser);
}
} else {
Collection<GrantedAuthority> authorities = new HashSet<>();
if (StrUtil.isNotBlank(roles)) {
@@ -112,6 +117,20 @@ public class LoginUserUtils {
return user;
}
public static LoginAppUser getLoginAppUser(SysUser sysUser) {
List<SysRole> sysRoles = sysUser.getRoles();
Collection<GrantedAuthority> authorities = new HashSet<>();
if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
}
return new LoginAppUser(sysUser.getId()
, sysUser.getUsername(), sysUser.getPassword()
, sysUser.getMobile(), sysUser.getPermissions()
, sysUser.getEnabled(), true, true, true
, authorities);
}
@SuppressWarnings("unchecked")
public static LoginAppUser getLoginAppUser(Map<String, Object> userObj) {
return new LoginAppUser(
@@ -1,3 +1,2 @@
com.central.common.feign.fallback.UserServiceFallbackFactory
com.central.common.lock.LockAspect
com.central.common.utils.SpringUtil
com.central.common.lock.LockAspect
@@ -1,18 +0,0 @@
package org.zlt.config;
import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;
/**
* web服务器配置
*
* @author zlt
* @version 1.0
* @date 2022/6/25
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
@@ -1,8 +1,7 @@
package org.zlt.controller;
import com.central.common.annotation.LoginUser;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -18,18 +17,18 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
/**
* 通过 @LoginUser 获取当前登录人
* 通过 LoginUserUtils 获取当前登录人
*/
@GetMapping("/test/auth")
public String auth(@LoginUser SysUser user) {
return "auth:" + user.getUsername();
public String auth() {
return "auth:" + LoginUserUtils.getCurrentUser(false).getUsername();
}
/**
* 通过 LoginUserContextHolder 获取当前登录人
*/
@GetMapping("/test/auth2")
public String auth() {
public String auth2() {
return "auth2:" + LoginUserContextHolder.getUser().getUsername();
}
@@ -97,10 +97,6 @@ knife4j:
context-path: /api-file
zlt:
oauth2:
token:
store:
type: redis
security:
ignore:
# 忽略认证的地址
@@ -111,7 +107,7 @@ zlt:
/api-uaa/images/**,
/api-uaa/js/**,
/login.html,
/user/login,
/user/login, /oauth/authorize,
/api-uaa/tokens/key
auth:
urlPermission:
-13
View File
@@ -50,14 +50,6 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@@ -71,11 +63,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
@@ -14,7 +14,6 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
@MapperScan(basePackages = "com.central.oauth.mapper")
@EnableFeignInterceptor
@EnableDiscoveryClient
//@EnableRedisHttpSession
@SpringBootApplication
public class UaaServerApp {
public static void main(String[] args) {
@@ -0,0 +1,48 @@
package com.central.oauth.component;
import com.central.common.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.core.endpoint.DefaultOAuth2AccessTokenResponseMapConverter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import java.util.Map;
/**
* @author zlt
* @version 1.0
* @date 2023/12/6
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomAccessTokenResponseHttpMessageConverter extends OAuth2AccessTokenResponseHttpMessageConverter {
private Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter = new DefaultOAuth2AccessTokenResponseMapConverter();
private static final ParameterizedTypeReference<Result<Map<String, Object>>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() {};
private final ObjectMapper objectMapper;
public CustomAccessTokenResponseHttpMessageConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter.convert(tokenResponse);
GenericHttpMessageConverter<Object> jsonMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
jsonMessageConverter.write(Result.succeed(tokenResponseParameters), STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
}
}
@@ -0,0 +1,35 @@
package com.central.oauth.component;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.LoginAppUser;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
/**
* token 输出增强
*
* @author: zlt
* @date: 2023/12/2
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomeOAuth2TokenCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> {
@Override
public void customize(OAuth2TokenClaimsContext context) {
OAuth2TokenClaimsSet.Builder claims = context.getClaims();
AbstractAuthenticationToken authenticationToken = context.getAuthorizationGrant();
if (authenticationToken instanceof BaseAuthenticationToken baseAuthenticationToken) {
LoginAppUser user = (LoginAppUser) context.getPrincipal().getPrincipal();
claims.claim(SecurityConstants.DETAILS_USER_ID, user.getId());
claims.claim(SecurityConstants.USERNAME, user.getUsername());
String account_type = (String)baseAuthenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
claims.claim(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, account_type);
}
}
}
@@ -0,0 +1,66 @@
package com.central.oauth.component;
import cn.hutool.core.util.ArrayUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.TenantContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 设置租户id过滤器
*
* @author zlt
* @date 2020/3/29
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class LoginProcessSetTenantFilter extends OncePerRequestFilter {
private static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
private RequestMatcher requiresAuthenticationRequestMatcher;
public LoginProcessSetTenantFilter() {
requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(SecurityConstants.OAUTH_LOGIN_PRO_URL, HttpMethod.POST.name());
}
/**
* 返回true代表不执行过滤器,false代表执行
*/
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
if (requiresAuthentication(request)) {
return false;
}
return true;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
try {
DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
if (savedRequest != null) {
String[] clientIds = savedRequest.getParameterValues("client_id");
if (ArrayUtil.isNotEmpty(clientIds)) {
//保存租户id
TenantContextHolder.setTenant(clientIds[0]);
}
}
chain.doFilter(request, response);
} finally {
TenantContextHolder.clear();
}
}
private boolean requiresAuthentication(HttpServletRequest request) {
return requiresAuthenticationRequestMatcher.matches(request);
}
}
@@ -0,0 +1,151 @@
package com.central.oauth.config;
import com.central.common.config.DefaultPasswordConfig;
import com.central.oauth.component.LoginProcessSetTenantFilter;
import com.central.oauth.service.IValidateCodeService;
import com.central.oauth.service.impl.RedisSecurityContextRepository;
import com.central.oauth.service.impl.RegisteredClientService;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.mobile.MobileAuthenticationConverter;
import com.central.oauth.support.mobile.MobileAuthenticationProvider;
import com.central.oauth.support.openid.OpenIdAuthenticationConverter;
import com.central.oauth.support.openid.OpenIdAuthenticationProvider;
import com.central.oauth.support.password.PasswordAuthenticationConverter;
import com.central.oauth.support.password.PasswordAuthenticationProvider;
import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationConverter;
import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider;
import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomBearerTokenResolver;
import com.central.oauth2.common.config.BaseSecurityConfig;
import com.central.oauth2.common.enums.TokenType;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.OAuth2ConfigurerUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.security.oauth2.server.authorization.web.authentication.DelegatingAuthenticationConverter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import java.util.Arrays;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@Import({BaseSecurityConfig.class, DefaultPasswordConfig.class})
public class AuthorizationServerConfig {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
private final AuthenticationFailureHandler authenticationFailureHandler;
private final CustomBearerTokenResolver customBearerTokenResolver;
private final AuthenticationEntryPoint authenticationEntryPoint;
private final LogoutHandler logoutHandler;
private final LogoutSuccessHandler logoutSuccessHandler;
private final AccessDeniedHandler oAuth2AccessDeniedHandler;
private final SecurityProperties securityProperties;
private final IValidateCodeService validateCodeService;
private final RegisteredClientService registeredClientService;
private final RedisSecurityContextRepository securityContextRepository;
private final AuthenticationSuccessHandler authenticationSuccessHandler;
/**
* spring security 默认的安全策略
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizeRequests -> {
// 授权服务器关闭basic认证
authorizeRequests
.requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.anyRequest().authenticated();
});
// 登录登出配置
http.apply(new FormIdentityLoginConfigurer(logoutSuccessHandler, logoutHandler));
// 登录的认证信息储存策略(redis)
http.securityContext(context -> context.securityContextRepository(securityContextRepository));
// 授权配置
OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(http);
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = OAuth2ConfigurerUtils.getTokenGenerator(http);
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();
http.apply(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> tokenEndpoint
// 注入自定义的授权认证Converter
.accessTokenRequestConverter(accessTokenRequestConverter())
// 登录失败处理器
.errorResponseHandler(authenticationFailureHandler)
// 登录成功处理器
.accessTokenResponseHandler(authenticationSuccessHandler)
// 自定义授权类型
.authenticationProvider(new PasswordAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder))
.authenticationProvider(new PasswordCodeAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder, validateCodeService))
.authenticationProvider(new OpenIdAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory))
.authenticationProvider(new MobileAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder))
)
// 开启OpenID Connect 1.0协议相关端点
.oidc(Customizer.withDefaults())
)
// 应用鉴权
.clientAuthentication(clientConfig -> clientConfig.errorResponseHandler(authenticationFailureHandler));
// 指定授权服务
http.apply(authorizationServerConfigurer
.authorizationService(authorizationService)
.authorizationEndpoint(endpoint -> endpoint
.errorResponseHandler(authenticationFailureHandler)
));
// 资源服务配置
http.oauth2ResourceServer(oauth2 -> {
oauth2.authenticationEntryPoint(authenticationEntryPoint)
.bearerTokenResolver(customBearerTokenResolver)
.accessDeniedHandler(oAuth2AccessDeniedHandler);
if (TokenType.JWT.getName().equals(securityProperties.getResourceServer().getTokenType())) {
oauth2.jwt(Customizer.withDefaults());
} else {
oauth2.opaqueToken(token -> token.introspector(new CustomAuthorizationServiceIntrospector(authorizationService)));
}
});
http.addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class);
// 缓存应用
registeredClientService.loadAllClientToCache();
return http.build();
}
private AuthenticationConverter accessTokenRequestConverter() {
return new DelegatingAuthenticationConverter(Arrays.asList(
new PasswordAuthenticationConverter(),
new PasswordCodeAuthenticationConverter(),
new OpenIdAuthenticationConverter(),
new MobileAuthenticationConverter()));
}
}
@@ -0,0 +1,45 @@
package com.central.oauth.config;
import com.central.common.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
/**
* @author: zlt
* @date: 2023/11/23
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@RequiredArgsConstructor
public class FormIdentityLoginConfigurer extends AbstractHttpConfigurer<FormIdentityLoginConfigurer, HttpSecurity> {
private final LogoutSuccessHandler logoutSuccessHandler;
private final LogoutHandler logoutHandler;
@Override
public void init(HttpSecurity http) throws Exception {
http.formLogin(formLogin -> formLogin
.loginPage(SecurityConstants.LOGIN_PAGE)
.loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler()))
.logout(logout -> logout
.logoutUrl(SecurityConstants.LOGOUT_URL)
.logoutSuccessHandler(logoutSuccessHandler)
.addLogoutHandler(logoutHandler)
.deleteCookies("JSESSIONID")
.clearAuthentication(true)
.invalidateHttpSession(true))
.headers(header -> header
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
}
}
@@ -1,23 +0,0 @@
package com.central.oauth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
*
* redis过期key监听器配置类
* @author zlt
*
*/
@Configuration
public class RedisListenerConfig {
@Bean
@Primary
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
return container;
}
}
@@ -0,0 +1,144 @@
package com.central.oauth.config;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.utils.ResponseUtil;
import com.central.oauth.component.CustomAccessTokenResponseHttpMessageConverter;
import com.central.oauth.component.CustomeOAuth2TokenCustomizer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.util.StandardSessionIdGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.CollectionUtils;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;
/**
* 服务安全相关配置
*
* @author: zlt
* @date: 2023/11/9
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
public class SecurityConfig {
/**
* token内容增强
*/
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer(){
return context -> {
JwtClaimsSet.Builder claims = context.getClaims();
claims.claim(SecurityConstants.LICENSE_NAME, SecurityConstants.PROJECT_LICENSE);
// 客户端模式不返回具体用户信息
if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType().getValue())) {
return;
}
if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
claims.claim(SecurityConstants.DETAILS_USER, context.getPrincipal().getPrincipal());
} else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
claims.claim(IdTokenClaimNames.AUTH_TIME, Date.from(Instant.now()));
StandardSessionIdGenerator standardSessionIdGenerator = new StandardSessionIdGenerator();
claims.claim("sid", standardSessionIdGenerator.generateSessionId());
}
};
}
/**
* 令牌生成规则实现
*/
@Bean
public OAuth2TokenGenerator oAuth2TokenGenerator(JwtEncoder jwtEncoder, OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer) {
JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
jwtGenerator.setJwtCustomizer(jwtTokenCustomizer);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer());
return new DelegatingOAuth2TokenGenerator(
jwtGenerator,
accessTokenGenerator,
new OAuth2RefreshTokenGenerator()
);
}
/**
* 授权服务信息配置
*/
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder()
.issuer(SecurityConstants.PROJECT_LICENSE)
.authorizationEndpoint(SecurityConstants.AUTH_CODE_URL)
.tokenEndpoint(SecurityConstants.OAUTH_TOKEN_URL)
.tokenIntrospectionEndpoint(SecurityConstants.OAUTH_CHECK_TOKEN_URL)
.build();
}
/**
* 授权错误处理
*/
@Bean
public AuthenticationFailureHandler authenticationFailureHandler(ObjectMapper objectMapper) {
return (request, response, authException) -> {
String msg = null;
if (StrUtil.isNotEmpty(authException.getMessage())) {
msg = authException.getMessage();
} else if (authException instanceof OAuth2AuthenticationException exception) {
msg = exception.getError().getErrorCode();
}
ResponseUtil.responseFailed(objectMapper, response, msg);
};
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(ObjectMapper objectMapper) {
return (request, response, authentication) -> {
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) authentication;
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
OAuth2AccessTokenResponse.Builder builder =
OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
.tokenType(accessToken.getTokenType())
.scopes(accessToken.getScopes());
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
}
if (refreshToken != null) {
builder.refreshToken(refreshToken.getTokenValue());
}
if (!CollectionUtils.isEmpty(additionalParameters)) {
builder.additionalParameters(additionalParameters);
}
OAuth2AccessTokenResponse accessTokenResponse = builder.build();
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
CustomAccessTokenResponseHttpMessageConverter converter = new CustomAccessTokenResponseHttpMessageConverter(objectMapper);
converter.write(accessTokenResponse, null, httpResponse);
};
}
}
@@ -1,14 +0,0 @@
package com.central.oauth.config;
/*import com.central.common.config.DefaultWebMvcConfig;
import org.springframework.context.annotation.Configuration;*/
/**
* @author zlt
* @date 2019/8/5
*/
/*
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
*/
@@ -2,13 +2,13 @@ package com.central.oauth.controller;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.oauth.dto.ClientDto;
import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService;
import com.central.oauth.service.impl.RegisteredClientService;
import com.central.oauth2.common.pojo.ClientDto;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -25,26 +25,26 @@ import java.util.Map;
@Tag(name = "应用")
@RestController
@RequestMapping("/clients")
@RequiredArgsConstructor
public class ClientController {
@Autowired
private IClientService clientService;
private final RegisteredClientService clientService;
@GetMapping("/list")
@Operation(summary = "应用列表")
public PageResult<Client> list(@RequestParam Map<String, Object> params) {
public PageResult<ClientDto> list(@RequestParam Map<String, Object> params) {
return clientService.listClient(params, true);
}
@GetMapping("/{id}")
@Operation(summary = "根据id获取应用")
public Client get(@PathVariable Long id) {
public ClientDto get(@PathVariable Long id) {
return clientService.getById(id);
}
@GetMapping("/all")
@Operation(summary = "所有应用")
public Result<List<Client>> allClient() {
PageResult<Client> page = clientService.listClient(Maps.newHashMap(), false);
public Result<List<ClientDto>> allClient() {
PageResult<ClientDto> page = clientService.listClient(Maps.newHashMap(), false);
return Result.succeed(page.getData());
}
@@ -56,7 +56,8 @@ public class ClientController {
@PostMapping("/saveOrUpdate")
@Operation(summary = "保存或者修改应用")
public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception {
return clientService.saveClient(clientDto);
public Result<String> saveOrUpdate(@RequestBody Client client) throws Exception {
clientService.saveClient(client);
return Result.succeed("操作成功");
}
}
@@ -0,0 +1,35 @@
package com.central.oauth.controller;
import com.central.common.model.PageResult;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
/**
* token管理接口
*
* @author zlt
*/
@Tag(name = "Token管理")
@Slf4j
@RestController
@RequestMapping("/tokens")
public class TokensController {
@Resource
private ITokensService tokensService;
@GetMapping("")
@Operation(summary = "token列表")
public PageResult<TokenVo> list(@RequestParam Map<String, Object> params, String tenantId) {
return tokensService.listTokens(params, tenantId);
}
}
@@ -1,18 +0,0 @@
package com.central.oauth.dto;
import com.central.oauth.model.Client;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Set;
@Setter
@Getter
public class ClientDto extends Client {
private static final long serialVersionUID = 1475637288060027265L;
private List<Long> permissionIds;
private Set<Long> serviceIds;
}
@@ -1,4 +1,4 @@
package com.central.oauth2.common.exception;
package com.central.oauth.exception;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
@@ -1,15 +0,0 @@
package com.central.oauth.exception;
import org.springframework.security.core.AuthenticationException;
/**
* 验证码异常
* @author zlt
*/
public class ValidateCodeException extends AuthenticationException {
private static final long serialVersionUID = -7285211528095468156L;
public ValidateCodeException(String msg) {
super(msg);
}
}
@@ -0,0 +1,50 @@
package com.central.oauth.handler;
import cn.hutool.core.util.StrUtil;
import com.central.oauth.utils.UsernameHolder;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.AuthUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author zlt
* @date 2018/10/17
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
@Component
public class OauthLogoutHandler implements LogoutHandler {
private final OAuth2AuthorizationService oAuth2AuthorizationService;
private final SecurityProperties securityProperties;
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Assert.notNull(oAuth2AuthorizationService, "oAuth2AuthorizationService must be set");
String token = request.getParameter("token");
if (StrUtil.isEmpty(token)) {
token = AuthUtils.extractToken(request);
}
if(StrUtil.isNotEmpty(token)){
OAuth2Authorization existingAccessToken = oAuth2AuthorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (existingAccessToken != null) {
if (securityProperties.getAuth().getUnifiedLogout()) {
UsernameHolder.setContext(existingAccessToken.getPrincipalName());
}
oAuth2AuthorizationService.remove(existingAccessToken);
log.info("remove existingAccessToken!", existingAccessToken.getAccessToken().getToken().getTokenType());
}
}
}
}
@@ -0,0 +1,51 @@
package com.central.oauth.handler;
import cn.hutool.core.util.StrUtil;
import com.central.common.utils.ResponseUtil;
import com.central.oauth.service.impl.UnifiedLogoutService;
import com.central.oauth2.common.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author zlt
* @date 2020/3/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
@Component
public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
private static final String REDIRECT_URL = "redirect_url";
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private final UnifiedLogoutService unifiedLogoutService;
private final SecurityProperties securityProperties;
private final ObjectMapper objectMapper;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
if (securityProperties.getAuth().getUnifiedLogout()) {
unifiedLogoutService.allLogout();
}
String redirectUri = request.getParameter(REDIRECT_URL);
if (StrUtil.isNotEmpty(redirectUri)) {
//重定向指定的地址
redirectStrategy.sendRedirect(request, response, redirectUri);
} else {
ResponseUtil.responseWriter(objectMapper, response, "登出成功", 0);
}
}
}
@@ -33,14 +33,9 @@ public class Client extends SuperEntity {
private String additionalInformation = "{}";
private String autoapprove = "true";
/**
* 是否支持id_token
* token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
*/
private Boolean supportIdToken = true;
/**
* id_token有效时间(s)
*/
@TableField(value = "id_token_validity")
private Integer idTokenValiditySeconds = 60;
private String tokenFormat = "reference";
private Long creatorId;
}
@@ -0,0 +1,54 @@
package com.central.oauth.model;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import java.util.function.Supplier;
/**
* @author: zlt
* @date: 2023/12/06
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public final class SupplierDeferredSecurityContext implements DeferredSecurityContext {
private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class);
private final Supplier<SecurityContext> supplier;
private final SecurityContextHolderStrategy strategy;
private SecurityContext securityContext;
private boolean missingContext;
public SupplierDeferredSecurityContext(Supplier<SecurityContext> supplier, SecurityContextHolderStrategy strategy) {
this.supplier = supplier;
this.strategy = strategy;
}
@Override
public SecurityContext get() {
init();
return this.securityContext;
}
@Override
public boolean isGenerated() {
init();
return this.missingContext;
}
private void init() {
if (this.securityContext != null) {
return;
}
this.securityContext = this.supplier.get();
this.missingContext = (this.securityContext == null);
if (this.missingContext) {
this.securityContext = this.strategy.createEmptyContext();
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Created %s", this.securityContext));
}
}
}
}
@@ -1,7 +1,6 @@
package com.central.oauth.service;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.service.ISuperService;
import com.central.oauth.model.Client;
@@ -14,7 +13,7 @@ import java.util.Map;
* Github: https://github.com/zlt2000
*/
public interface IClientService extends ISuperService<Client> {
Result saveClient(Client clientDto) throws Exception;
void saveClient(Client clientDto) throws Exception;
/**
* 查询应用列表
@@ -26,6 +25,4 @@ public interface IClientService extends ISuperService<Client> {
void delClient(long id);
Client loadClientByClientId(String clientId);
void loadAllClientToCache();
}
@@ -3,11 +3,9 @@ package com.central.oauth.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.SecurityConstants;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.oauth.mapper.ClientMapper;
import com.central.oauth.model.Client;
@@ -15,9 +13,6 @@ import com.central.oauth.service.IClientService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@@ -36,14 +31,12 @@ import java.util.Map;
public class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> implements IClientService {
private final static String LOCK_KEY_CLIENTID = "clientId:";
private final RedissonClient redisson;
private final PasswordEncoder passwordEncoder;
private final DistributedLock lock;
@Override
public Result saveClient(Client client) throws Exception {
public void saveClient(Client client) throws Exception {
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
String clientId = client.getClientId();
if (client.getId() == null) {
@@ -53,10 +46,6 @@ public class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> im
, LOCK_KEY_CLIENTID+clientId
, new QueryWrapper<Client>().eq("client_id", clientId)
, clientId + "已存在");
redisson.getBucket(clientRedisKey(clientId)).set(client);
return Result.succeed("操作成功");
}
@Override
@@ -74,32 +63,13 @@ public class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> im
@Override
public void delClient(long id) {
String clientId = baseMapper.selectById(id).getClientId();
baseMapper.deleteById(id);
redisson.getBucket(clientRedisKey(clientId)).delete();
}
@Override
public Client loadClientByClientId(String clientId) {
RBucket<Client> clientBucket = redisson.getBucket(clientRedisKey(clientId));
Client client = clientBucket.get();
if (client != null) {
return client;
}
QueryWrapper<Client> wrapper = Wrappers.query();
wrapper.eq("client_id", clientId);
client = this.getOne(wrapper);
clientBucket.set(client);
return client;
}
@Override
public void loadAllClientToCache() {
List<Client> clientList = this.list();
clientList.forEach(c -> redisson.getBucket(clientRedisKey(c.getClientId())).set(c));
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
return this.getOne(wrapper);
}
}
@@ -0,0 +1,90 @@
package com.central.oauth.service.impl;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.central.oauth2.common.pojo.ClientDto;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.stereotype.Component;
import java.time.Duration;
/**
* @author: zlt
* @date: 2023/08/04
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@RequiredArgsConstructor
@Component
public class CustomRegisteredClientRepository implements RegisteredClientRepository {
private final RegisteredClientService clientService;
@Override
public void save(RegisteredClient registeredClient) {
}
@Override
public RegisteredClient findById(String id) {
return this.findByClientId(id);
}
@Override
public RegisteredClient findByClientId(String clientId) {
ClientDto clientObj = clientService.loadClientByClientId(clientId);
if (clientObj == null) {
return null;
}
RegisteredClient.Builder builder = RegisteredClient.withId(clientObj.getClientId())
.clientId(clientObj.getClientId())
.clientSecret(clientObj.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
if (StrUtil.isNotBlank(clientObj.getAuthorizedGrantTypes())) {
for (String authorizedGrantType : clientObj.getAuthorizedGrantTypes().split(StrUtil.COMMA)) {
builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
}
}
if (StrUtil.isNotBlank(clientObj.getWebServerRedirectUri())) {
for (String redirectUri : clientObj.getWebServerRedirectUri().split(StrUtil.COMMA)) {
builder.redirectUri(redirectUri);
}
}
if (StrUtil.isNotBlank(clientObj.getScope())) {
for (String scope : clientObj.getScope().split(StrUtil.COMMA)) {
builder.scope(scope);
}
}
OAuth2TokenFormat tokenFormat;
if (OAuth2TokenFormat.SELF_CONTAINED.getValue().equals(clientObj.getTokenFormat())) {
tokenFormat = OAuth2TokenFormat.SELF_CONTAINED;
} else {
tokenFormat = OAuth2TokenFormat.REFERENCE;
}
return builder
.tokenSettings(
TokenSettings.builder()
.accessTokenFormat(tokenFormat)
.accessTokenTimeToLive(Duration.ofSeconds(clientObj.getAccessTokenValiditySeconds()))
.refreshTokenTimeToLive(Duration.ofSeconds(clientObj.getRefreshTokenValiditySeconds()))
.build()
)
.clientSettings(
ClientSettings.builder()
.requireAuthorizationConsent(!BooleanUtil.toBoolean(clientObj.getAutoapprove()))
.build()
)
.build();
}
}
@@ -0,0 +1,55 @@
package com.central.oauth.service.impl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.time.Duration;
/**
* @author: zlt
* @date: 2023/11/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@RequiredArgsConstructor
@Component
public class RedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
private final RedissonClient redissonClient;;
private final static Long TIMEOUT = 10L;
@Override
public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redissonClient.getBucket(buildKey(authorizationConsent))
.set(authorizationConsent, Duration.ofMinutes(TIMEOUT));
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redissonClient.getBucket(buildKey(authorizationConsent)).delete();
}
@Override
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (OAuth2AuthorizationConsent) redissonClient.getBucket(buildKey(registeredClientId, principalName)).get();
}
private static String buildKey(String registeredClientId, String principalName) {
return "token:consent:" + registeredClientId + ":" + principalName;
}
private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
}
@@ -0,0 +1,138 @@
package com.central.oauth.service.impl;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth.model.SupplierDeferredSecurityContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.function.Supplier;
/**
* 基于redis存储认证信息,解决多节点uaa单点登录信息互通
*
* @author: zlt
* @date: 2023/12/06
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
@RequiredArgsConstructor
public class RedisSecurityContextRepository implements SecurityContextRepository {
/**
* 认证信息存储前缀
*/
public static final String SECURITY_CONTEXT_PREFIX_KEY = "security_context:";
/**
* 随机字符串请求头名字
*/
public static final String NONCE_HEADER_NAME = "nonceId";
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final RedissonClient redissonClient;
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
throw new UnsupportedOperationException("Method deprecated.");
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return;
}
// 如果当前的context是空的,则移除
SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
RBucket<SecurityContext> rBucket = this.getBucket(nonce);
if (emptyContext.equals(context)) {
rBucket.delete();
} else {
// 保存认证信息
rBucket.set(context, Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
}
}
@Override
public boolean containsContext(HttpServletRequest request) {
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return false;
}
// 检验当前请求是否有认证信息
return this.getBucket(nonce).get() != null;
}
@Override
public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
Supplier<SecurityContext> supplier = () -> readSecurityContextFromRedis(request);
return new SupplierDeferredSecurityContext(supplier, this.securityContextHolderStrategy);
}
/**
* 从redis中获取认证信息
*
* @param request 当前请求
* @return 认证信息
*/
private SecurityContext readSecurityContextFromRedis(HttpServletRequest request) {
if (request == null) {
return null;
}
String nonce = getNonce(request);
if (StrUtil.isEmpty(nonce)) {
return null;
}
// 根据缓存id获取认证信息
RBucket<SecurityContext> rBucket = this.getBucket(nonce);
SecurityContext context = rBucket.get();
if (context != null) {
rBucket.expire(Duration.ofSeconds(SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS));
}
return context;
}
/**
* 先从请求头中找,找不到去请求参数中找,找不到获取当前session的id
* 2023-07-11新增逻辑:获取当前session的sessionId
*
* @param request 当前请求
* @return 随机字符串(sessionId),这个字符串本来是前端生成,现在改为后端获取的sessionId
*/
private String getNonce(HttpServletRequest request) {
String nonce = request.getHeader(NONCE_HEADER_NAME);
if (StrUtil.isEmpty(nonce)) {
nonce = request.getParameter(NONCE_HEADER_NAME);
if (StrUtil.isEmpty(nonce)) {
HttpSession session = request.getSession(Boolean.FALSE);
if (session != null) {
nonce = session.getId();
}
}
}
return nonce;
}
private RBucket<SecurityContext> getBucket(String nonce) {
return redissonClient.getBucket(SECURITY_CONTEXT_PREFIX_KEY + nonce, AUTH_CODEC);
}
}
@@ -0,0 +1,102 @@
package com.central.oauth.service.impl;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
import com.central.common.redis.template.RedisRepository;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.stereotype.Service;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* token管理服务(redis token)
*
* @author zlt
* @date 2019/7/12
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class RedisTokensServiceImpl implements ITokensService {
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private static final String AUTHORIZATION = "token";
private final RedissonClient redisson;
@Override
public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) {
Integer page = MapUtils.getInteger(params, "page");
Integer limit = MapUtils.getInteger(params, "limit");
int[] startEnds = PageUtil.transToStartEnd(page-1, limit);
//根据请求参数生成redis的key
String redisKey = getRedisKey(params, clientId);
RList<String> tokenList = redisson.getList(redisKey);
long size = tokenList.size();
List<TokenVo> result = new ArrayList<>(limit);
//查询token集合
List<String> tokens = tokenList.range(startEnds[0], startEnds[1]-1);
if (tokens != null) {
for (String token : tokens) {
//构造token对象
TokenVo tokenVo = new TokenVo();
tokenVo.setTokenValue(token);
//获取用户信息
RBucket<OAuth2Authorization> rBucket = redisson.getBucket(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, token), AUTH_CODEC);
OAuth2Authorization authorization = rBucket.get();
if (authorization != null) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
if (accessToken != null && accessToken.getExpiresAt() != null) {
tokenVo.setExpiration(Date.from(accessToken.getExpiresAt().plus(8, ChronoUnit.HOURS)));
}
tokenVo.setUsername(authorization.getPrincipalName());
tokenVo.setClientId(authorization.getRegisteredClientId());
tokenVo.setGrantType(authorization.getAuthorizationGrantType().getValue());
String accountType = (String)authorization.getAttributes().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
tokenVo.setAccountType(accountType);
}
result.add(tokenVo);
}
}
return PageResult.<TokenVo>builder().data(result).code(0).count(size).build();
}
/**
* 根据请求参数生成redis的key
*/
private String getRedisKey(Map<String, Object> params, String clientId) {
String result;
String username = MapUtils.getString(params, "username");
if (StrUtil.isNotEmpty(username)) {
result = this.buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username);
} else {
result = this.buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId);
}
return result;
}
private String buildKey(String type, String id) {
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
}
@@ -0,0 +1,89 @@
package com.central.oauth.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService;
import com.central.oauth2.common.pojo.ClientDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author zlt
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class RegisteredClientService {
private final IClientService clientService;
private final RedissonClient redisson;
public void saveClient(Client client) throws Exception {
clientService.saveClient(client);
redisson.getBucket(clientRedisKey(client.getClientId())).set(client);
}
public PageResult<ClientDto> listClient(Map<String, Object> params, boolean isPage) {
PageResult<Client> clientPage = clientService.listClient(params, isPage);
PageResult<ClientDto> result = new PageResult<>();
result.setCode(clientPage.getCode());
result.setCount(clientPage.getCount());
result.setData(BeanUtil.copyToList(clientPage.getData(), ClientDto.class));
return result;
}
public ClientDto getById(long id) {
return BeanUtil.copyProperties(clientService.getById(id), ClientDto.class);
}
public void delClient(long id) {
Client client = clientService.getById(id);
if (client != null) {
clientService.delClient(id);
redisson.getBucket(clientRedisKey(client.getClientId())).delete();
}
}
public ClientDto loadClientByClientId(String clientId) {
RBucket<ClientDto> clientBucket = redisson.getBucket(clientRedisKey(clientId));
ClientDto clientDto = clientBucket.get();
if (clientDto != null) {
return clientDto;
}
Client clientObj = clientService.loadClientByClientId(clientId);
clientDto = BeanUtil.copyProperties(clientObj, ClientDto.class);
clientBucket.set(clientDto);
return clientDto;
}
public void loadAllClientToCache() {
List<Client> clientList = clientService.list();
clientList.forEach(c -> {
ClientDto clientDto = BeanUtil.copyProperties(c, ClientDto.class);;
redisson.getBucket(clientRedisKey(c.getClientId())).set(clientDto);
});
}
public List<ClientDto> list() {
return BeanUtil.copyToList(clientService.list(), ClientDto.class);
}
public ClientDto getRegisteredClientByClientId(String clientId) {
Client clientObj = clientService.loadClientByClientId(clientId);
return BeanUtil.copyProperties(clientObj, ClientDto.class);
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
@@ -0,0 +1,125 @@
package com.central.oauth.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.central.oauth.utils.UsernameHolder;
import com.central.oauth2.common.pojo.ClientDto;
import com.central.oauth2.common.service.impl.RedisOAuth2AuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 统一登出服务
*
* @author zlt
* @version 1.0
* @date 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
public class UnifiedLogoutService {
private final static String LOGOUT_NOTIFY_URL_KEY = "LOGOUT_NOTIFY_URL_LIST";
private final RestTemplate restTemplate;
private final TaskExecutor taskExecutor;
private final RegisteredClientService clientService;
private final RedisOAuth2AuthorizationService authorizationService;
public UnifiedLogoutService(RestTemplate restTemplate, TaskExecutor taskExecutor
, RegisteredClientService clientService
, @Autowired(required = false) RedisOAuth2AuthorizationService authorizationService) {
this.restTemplate = restTemplate;
this.taskExecutor = taskExecutor;
this.clientService = clientService;
this.authorizationService = authorizationService;
}
public void allLogout() {
if (authorizationService == null) {
throw new RuntimeException("the 'zlt.oauth2.token.store' parameter must be redis");
}
Set<String> urls = this.getLogoutNotifyUrl();
for (String url : urls) {
taskExecutor.execute(() -> {
try {
restTemplate.getForObject(url, Void.class);
} catch (Exception e) {
log.warn(e.getMessage());
}
});
}
}
/**
* 获取登出需要通知的地址集合
*/
private Set<String> getLogoutNotifyUrl() {
String username = UsernameHolder.getContext();
Set<String> logoutNotifyUrls = new HashSet<>();
try {
List<ClientDto> clientDetails = clientService.list();
Map<String, Object> informationMap;
for (ClientDto client : clientDetails) {
informationMap = this.getInfoMap(client.getAdditionalInformation());
String urls = (String)informationMap.get(LOGOUT_NOTIFY_URL_KEY);
if (StrUtil.isNotEmpty(urls)) {
List<String> tokens = authorizationService.findTokensByClientIdAndUserName(client.getClientId(), username);
if (CollUtil.isNotEmpty(tokens)) {
//注销所有该用户名下的token
tokens.forEach(authorizationService::remove);
String tokenStr = getTokenValueStr(tokens);
logoutNotifyUrls.addAll(generateNotifyUrls(urls.split(","), tokenStr));
}
}
}
} finally {
UsernameHolder.clearContext();
}
return logoutNotifyUrls;
}
private String getTokenValueStr(List<String> tokens) {
if (CollUtil.isNotEmpty(tokens)) {
return StrUtil.join( ",", tokens);
}
return null;
}
private Set<String> generateNotifyUrls(String[] urls, String tokenStr) {
Set<String> urlSet = new HashSet(urls.length);
for (String url : urls) {
StringBuilder urlBuilder = new StringBuilder(url);
if (url.contains("?")) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
}
urlBuilder.append("tokens=").append(tokenStr);
urlSet.add(urlBuilder.toString());
}
return urlSet;
}
private Map<String, Object> getInfoMap(String additionalInformation) {
if (StrUtil.isNotEmpty(additionalInformation)) {
return JSONUtil.toBean(additionalInformation, Map.class);
}
return Map.of();
}
}
@@ -0,0 +1,53 @@
package com.central.oauth.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth.service.ZltUserDetailsService;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.util.AuthUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 用户service工厂
*
* @author zlt
* @version 1.0
* @date 2021/7/24
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
public class UserDetailServiceFactory {
private static final String ERROR_MSG = "Cannot find the implementation class for the account type {}";
@Resource
private List<ZltUserDetailsService> userDetailsServices;
public ZltUserDetailsService getService(Authentication authentication) {
String accountType = AuthUtils.getAccountType(authentication);
return this.getService(accountType);
}
public ZltUserDetailsService getService(String accountType) {
if (StrUtil.isEmpty(accountType)) {
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
}
log.info("UserDetailServiceFactory.getService:{}", accountType);
if (CollUtil.isNotEmpty(userDetailsServices)) {
for (ZltUserDetailsService userService : userDetailsServices) {
if (userService.supports(accountType)) {
return userService;
}
}
}
throw new CustomOAuth2AuthenticationException(StrUtil.format(ERROR_MSG, accountType));
}
}
@@ -2,7 +2,8 @@ package com.central.oauth.service.impl;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils;
import com.central.oauth.service.ZltUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
@@ -33,29 +34,31 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
LoginAppUser loginAppUser = userService.findByUsername(username);
if (loginAppUser == null) {
SysUser sysUser = userService.findByUsername(username);
if (sysUser == null) {
throw new InternalAuthenticationServiceException("用户名或密码错误");
}
return checkUser(loginAppUser);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public UserDetails loadUserByUserId(String openId) {
LoginAppUser loginAppUser = userService.findByOpenId(openId);
return checkUser(loginAppUser);
SysUser sysUser = userService.findByOpenId(openId);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public UserDetails loadUserByMobile(String mobile) {
LoginAppUser loginAppUser = userService.findByMobile(mobile);
return checkUser(loginAppUser);
SysUser sysUser = userService.findByMobile(mobile);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
private LoginAppUser checkUser(LoginAppUser loginAppUser) {
if (loginAppUser != null && !loginAppUser.isEnabled()) {
private void checkUser(SysUser sysUser) {
if (sysUser != null && !sysUser.getEnabled()) {
throw new DisabledException("用户已作废");
}
return loginAppUser;
}
}
@@ -4,16 +4,17 @@ import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.Result;
import com.central.common.redis.template.RedisRepository;
import com.central.oauth.exception.ValidateCodeException;
import com.central.common.model.SysUser;
import com.central.oauth.service.IValidateCodeService;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.Duration;
/**
* @author zlt
@@ -23,13 +24,12 @@ import javax.annotation.Resource;
* Github: https://github.com/zlt2000
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class ValidateCodeServiceImpl implements IValidateCodeService {
@Autowired
private RedisRepository redisRepository;
private final RedissonClient redisson;
@Resource
private UserService userService;
private final UserService userService;
/**
* 保存用户验证码,和randomStr绑定
@@ -39,7 +39,8 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public void saveImageCode(String deviceId, String imageCode) {
redisRepository.setExpire(buildKey(deviceId), imageCode, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
this.getBucket(deviceId)
.set(imageCode, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
}
/**
@@ -55,13 +56,14 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public Result<String> sendSmsCode(String mobile) {
Object tempCode = redisRepository.get(buildKey(mobile));
RBucket<String> rBucket = this.getBucket(mobile);
Object tempCode = rBucket.get();
if (tempCode != null) {
log.error("用户:{}验证码未失效{}", mobile, tempCode);
return Result.failed("验证码未失效,请失效后再次申请");
}
LoginAppUser user = userService.findByMobile(mobile);
SysUser user = userService.findByMobile(mobile);
if (user == null) {
log.error("根据用户手机号{}查询用户为空", mobile);
return Result.failed("手机号不存在");
@@ -69,7 +71,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
String code = RandomUtil.randomNumbers(4);
log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
redisRepository.setExpire(buildKey(mobile), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
rBucket.set(code, Duration.ofSeconds(SecurityConstants.DEFAULT_IMAGE_EXPIRE));
return Result.succeed("true");
}
@@ -79,7 +81,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public String getCode(String deviceId) {
return (String)redisRepository.get(buildKey(deviceId));
return this.getBucket(deviceId).get();
}
/**
@@ -88,7 +90,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
*/
@Override
public void remove(String deviceId) {
redisRepository.del(buildKey(deviceId));
this.getBucket(deviceId).delete();
}
/**
@@ -97,19 +99,19 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
@Override
public void validate(String deviceId, String validCode) {
if (StrUtil.isBlank(deviceId)) {
throw new ValidateCodeException("请在请求参数中携带deviceId参数");
throw new CustomOAuth2AuthenticationException("请在请求参数中携带deviceId参数");
}
String code = this.getCode(deviceId);
if (StrUtil.isBlank(validCode)) {
throw new ValidateCodeException("请填写验证码");
throw new CustomOAuth2AuthenticationException("请填写验证码");
}
if (code == null) {
throw new ValidateCodeException("验证码不存在或已过期");
throw new CustomOAuth2AuthenticationException("验证码不存在或已过期");
}
if (!StrUtil.equals(code, validCode.toLowerCase())) {
throw new ValidateCodeException("验证码不正确");
throw new CustomOAuth2AuthenticationException("验证码不正确");
}
this.remove(deviceId);
@@ -118,4 +120,8 @@ public class ValidateCodeServiceImpl implements IValidateCodeService {
private String buildKey(String deviceId) {
return SecurityConstants.DEFAULT_CODE_KEY + ":" + deviceId;
}
private RBucket<String> getBucket(String deviceId) {
return redisson.getBucket(buildKey(deviceId));
}
}
@@ -0,0 +1,88 @@
package com.central.oauth.support.base;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public abstract class BaseAuthenticationConverter implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!this.supportGrantType().equals(grantType)) {
return null;
}
MultiValueMap<String, String> parameters = OAuthEndpointUtils.getParameters(request);
return this.getAuthentication(parameters);
}
public Authentication getAuthentication(MultiValueMap<String, String> parameters) {
Set<String> requestScopes = this.getRequestScopes(parameters);
Map<String, Object> additionalParameters = getAdditionalParameters(parameters, this.paramNames());
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
BaseAuthenticationToken baseToken = this.getToken(parameters);
baseToken.setScopes(requestScopes);
baseToken.setAdditionalParameters(additionalParameters);
baseToken.setClientPrincipal(clientPrincipal);
return baseToken;
};
public Set<String> getRequestScopes(MultiValueMap<String, String> parameters) {
String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
Set<String> requestedScopes = null;
if (StrUtil.isNotEmpty(scope)) {
requestedScopes = new HashSet<>(
Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
} else {
requestedScopes = Collections.emptySet();
}
return requestedScopes;
}
public Map<String, Object> getAdditionalParameters(MultiValueMap<String, String> parameters, List<String> paramName) {
Map<String, Object> additionalParameters = new HashMap<>();
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
!key.equals(OAuth2ParameterNames.SCOPE)) {
boolean isAdd = true;
if (ArrayUtil.isNotEmpty(paramName)) {
for (String name : paramName) {
if (key.equals(name)) {
isAdd = false;
}
}
}
if (isAdd) {
additionalParameters.put(key, value.get(0));
}
}
});
return additionalParameters;
}
protected abstract String supportGrantType();
protected abstract List<String> paramNames();
protected abstract BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters);
}
@@ -0,0 +1,201 @@
package com.central.oauth.support.base;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 基础provider
*
* @author zlt
* @version 1.0
* @date 2023/11/18
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public abstract class BaseAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.3";
private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE = new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
private final OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
public BaseAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) {
BaseAuthenticationToken authToken = (BaseAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(authToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
Set<String> authorizedScopes = authToken.getScopes();
if (!CollectionUtils.isEmpty(authToken.getScopes())) {
for (String requestedScope : authToken.getScopes()) {
if (!registeredClient.getScopes().contains(requestedScope)) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE);
}
}
}
// 执行登录验证逻辑
Authentication principal = this.getPrincipal(authentication);
String accountType = (String)authToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
if (StrUtil.isEmpty(accountType)) {
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
authToken.getAdditionalParameters().put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
}
// @formatter:off
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(principal)
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizedScopes(authorizedScopes)
.authorizationGrantType(this.grantType())
.authorizationGrant(authToken);
// @formatter:on
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization
.withRegisteredClient(registeredClient)
.principalName(principal.getName())
.attribute(Principal.class.getName(), principal)
.attribute(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType)
.authorizationGrantType(this.grantType())
.authorizedScopes(authorizedScopes);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the access token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
authorizationBuilder.id(accessToken.getTokenValue());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) ->
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// Do not issue refresh token to public client
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the refresh token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
// ----- ID token -----
OidcIdToken idToken;
if (authorizedScopes.contains(OidcScopes.OPENID)) {
// @formatter:off
tokenContext = tokenContextBuilder
.tokenType(ID_TOKEN_TOKEN_TYPE)
.authorization(authorizationBuilder.build()) // ID token customizer may need access to the access token and/or refresh token
.build();
// @formatter:on
OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedIdToken instanceof Jwt)) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"The token generator failed to generate the ID token.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
authorizationBuilder.token(idToken, (metadata) ->
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
} else {
idToken = null;
}
OAuth2Authorization authorization = authorizationBuilder.build();
this.authorizationService.save(authorization);
Map<String, Object> additionalParameters = Collections.emptyMap();
if (idToken != null) {
additionalParameters = new HashMap<>();
additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
}
return new OAuth2AccessTokenAuthenticationToken(
registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
}
private OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(
BaseAuthenticationToken authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getClientPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getClientPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 执行登录验证逻辑
*/
protected abstract Authentication getPrincipal(Authentication authentication);
/**
* 获取 GrantType
*/
protected abstract AuthorizationGrantType grantType();
}
@@ -0,0 +1,38 @@
package com.central.oauth.support.mobile;
import com.central.oauth.support.base.BaseAuthenticationConverter;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import com.central.oauth2.common.token.MobileAuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import java.util.List;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class MobileAuthenticationConverter extends BaseAuthenticationConverter {
private final static String PARAM_MOBILE= "mobile";
@Override
protected String supportGrantType() {
return MobileAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(PARAM_MOBILE, OAuth2ParameterNames.PASSWORD);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String mobile = OAuthEndpointUtils.getParam(parameters, PARAM_MOBILE);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
return new MobileAuthenticationToken(mobile, password);
}
}
@@ -0,0 +1,67 @@
package com.central.oauth.support.mobile;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.token.MobileAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
/**
* @author zlt
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class MobileAuthenticationProvider extends BaseAuthenticationProvider {
private UserDetailServiceFactory userDetailsServiceFactory;
private PasswordEncoder passwordEncoder;
public MobileAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
}
@Override
public boolean supports(Class<?> authentication) {
return MobileAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {
MobileAuthenticationToken authToken = (MobileAuthenticationToken) authentication;
String mobile = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByMobile(mobile);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("手机号或密码错误");
}
return new MobileAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
}
@Override
protected AuthorizationGrantType grantType() {
return MobileAuthenticationToken.GRANT_TYPE;
}
}
@@ -0,0 +1,36 @@
package com.central.oauth.support.openid;
import com.central.oauth.support.base.BaseAuthenticationConverter;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
import org.springframework.util.MultiValueMap;
import java.util.List;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OpenIdAuthenticationConverter extends BaseAuthenticationConverter {
private final static String PARAM_OPENID = "openId";
@Override
protected String supportGrantType() {
return OpenIdAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(PARAM_OPENID);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String openId = OAuthEndpointUtils.getParam(parameters, PARAM_OPENID);
return new OpenIdAuthenticationToken(openId);
}
}
@@ -0,0 +1,63 @@
package com.central.oauth.support.openid;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class OpenIdAuthenticationProvider extends BaseAuthenticationProvider {
private UserDetailServiceFactory userDetailsServiceFactory;
public OpenIdAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
}
@Override
public boolean supports(Class<?> authentication) {
return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {
OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
String openId = (String) authToken.getPrincipal();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUserId(openId);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null) {
throw new CustomOAuth2AuthenticationException("openId错误");
}
return new OpenIdAuthenticationToken(userDetails, userDetails.getAuthorities());
}
@Override
protected AuthorizationGrantType grantType() {
return OpenIdAuthenticationToken.GRANT_TYPE;
}
}
@@ -0,0 +1,36 @@
package com.central.oauth.support.password;
import com.central.oauth.support.base.BaseAuthenticationConverter;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import com.central.oauth2.common.token.PasswordAuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import java.util.List;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class PasswordAuthenticationConverter extends BaseAuthenticationConverter {
@Override
protected String supportGrantType() {
return PasswordAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(OAuth2ParameterNames.USERNAME, OAuth2ParameterNames.PASSWORD);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
return new PasswordAuthenticationToken(username, password);
}
}
@@ -0,0 +1,71 @@
package com.central.oauth.support.password;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.token.PasswordAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
/**
* 用户名密码 provider
*
* @author zlt
* @version 1.0
* @date 2023/11/18
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class PasswordAuthenticationProvider extends BaseAuthenticationProvider {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
public PasswordAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
}
@Override
public boolean supports(Class<?> authentication) {
return PasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {
PasswordAuthenticationToken authToken = (PasswordAuthenticationToken) authentication;
String username = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("用户名或密码错误");
}
return new PasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
}
@Override
protected AuthorizationGrantType grantType() {
return PasswordAuthenticationToken.GRANT_TYPE;
}
}
@@ -0,0 +1,41 @@
package com.central.oauth.support.passwordCode;
import com.central.oauth.support.base.BaseAuthenticationConverter;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import com.central.oauth2.common.token.PasswordCodeAuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import java.util.List;
/**
* @author: zlt
* @date: 2023/11/18
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class PasswordCodeAuthenticationConverter extends BaseAuthenticationConverter {
private final static String PARAM_DEVICEID = "deviceId";
private final static String PARAM_VALIDCODE = "validCode";
@Override
protected String supportGrantType() {
return PasswordCodeAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(OAuth2ParameterNames.USERNAME, OAuth2ParameterNames.PASSWORD
, PARAM_DEVICEID, PARAM_VALIDCODE);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String username = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.USERNAME);
String password = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.PASSWORD);
String deviceId = OAuthEndpointUtils.getParam(parameters, PARAM_DEVICEID);
String validCode = OAuthEndpointUtils.getParam(parameters, PARAM_VALIDCODE);
return new PasswordCodeAuthenticationToken(username, password, deviceId, validCode);
}
}
@@ -0,0 +1,81 @@
package com.central.oauth.support.passwordCode;
import com.central.oauth.service.IValidateCodeService;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.token.PasswordCodeAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
/**
* 用户名密码+图像验证码 provider
*
* @author zlt
* @version 1.0
* @date 2023/11/25
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class PasswordCodeAuthenticationProvider extends BaseAuthenticationProvider {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
private final IValidateCodeService validateCodeService;
public PasswordCodeAuthenticationProvider(OAuth2AuthorizationService authorizationService
, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
, UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder
, IValidateCodeService validateCodeService) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
this.validateCodeService = validateCodeService;
}
@Override
public boolean supports(Class<?> authentication) {
return PasswordCodeAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {
PasswordCodeAuthenticationToken authToken = (PasswordCodeAuthenticationToken) authentication;
String deviceId = authToken.getDeviceId();
String validCode = authToken.getValidCode();
//校验图形验证码
validateCodeService.validate(deviceId, validCode);
String username = (String) authToken.getPrincipal();
String password = authToken.getCredentials();
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByUsername(username);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
throw new CustomOAuth2AuthenticationException("用户名或密码错误");
}
return new PasswordCodeAuthenticationToken(userDetails, userDetails.getPassword(), deviceId, userDetails.getAuthorities());
}
@Override
protected AuthorizationGrantType grantType() {
return PasswordCodeAuthenticationToken.GRANT_TYPE;
}
}
@@ -0,0 +1,197 @@
package com.central.oauth.utils;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OAuth2ConfigurerUtils {
private OAuth2ConfigurerUtils() {
}
public static RegisteredClientRepository getRegisteredClientRepository(HttpSecurity httpSecurity) {
RegisteredClientRepository registeredClientRepository = httpSecurity.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) {
registeredClientRepository = getBean(httpSecurity, RegisteredClientRepository.class);
httpSecurity.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
}
return registeredClientRepository;
}
public static OAuth2AuthorizationService getAuthorizationService(HttpSecurity httpSecurity) {
OAuth2AuthorizationService authorizationService = httpSecurity.getSharedObject(OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = getOptionalBean(httpSecurity, OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = new InMemoryOAuth2AuthorizationService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationService.class, authorizationService);
}
return authorizationService;
}
public static OAuth2AuthorizationConsentService getAuthorizationConsentService(HttpSecurity httpSecurity) {
OAuth2AuthorizationConsentService authorizationConsentService = httpSecurity.getSharedObject(OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = getOptionalBean(httpSecurity, OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = new InMemoryOAuth2AuthorizationConsentService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationConsentService.class, authorizationConsentService);
}
return authorizationConsentService;
}
@SuppressWarnings("unchecked")
public static OAuth2TokenGenerator<? extends OAuth2Token> getTokenGenerator(HttpSecurity httpSecurity) {
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = httpSecurity.getSharedObject(OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
tokenGenerator = getOptionalBean(httpSecurity, OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
JwtGenerator jwtGenerator = getJwtGenerator(httpSecurity);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer = getAccessTokenCustomizer(httpSecurity);
if (accessTokenCustomizer != null) {
accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer);
}
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
if (jwtGenerator != null) {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
} else {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
accessTokenGenerator, refreshTokenGenerator);
}
}
httpSecurity.setSharedObject(OAuth2TokenGenerator.class, tokenGenerator);
}
return tokenGenerator;
}
private static JwtGenerator getJwtGenerator(HttpSecurity httpSecurity) {
JwtGenerator jwtGenerator = httpSecurity.getSharedObject(JwtGenerator.class);
if (jwtGenerator == null) {
JwtEncoder jwtEncoder = getJwtEncoder(httpSecurity);
if (jwtEncoder != null) {
jwtGenerator = new JwtGenerator(jwtEncoder);
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = getJwtCustomizer(httpSecurity);
if (jwtCustomizer != null) {
jwtGenerator.setJwtCustomizer(jwtCustomizer);
}
httpSecurity.setSharedObject(JwtGenerator.class, jwtGenerator);
}
}
return jwtGenerator;
}
private static JwtEncoder getJwtEncoder(HttpSecurity httpSecurity) {
JwtEncoder jwtEncoder = httpSecurity.getSharedObject(JwtEncoder.class);
if (jwtEncoder == null) {
jwtEncoder = getOptionalBean(httpSecurity, JwtEncoder.class);
if (jwtEncoder == null) {
JWKSource<SecurityContext> jwkSource = getJwkSource(httpSecurity);
if (jwkSource != null) {
jwtEncoder = new NimbusJwtEncoder(jwkSource);
}
}
if (jwtEncoder != null) {
httpSecurity.setSharedObject(JwtEncoder.class, jwtEncoder);
}
}
return jwtEncoder;
}
@SuppressWarnings("unchecked")
public static JWKSource<SecurityContext> getJwkSource(HttpSecurity httpSecurity) {
JWKSource<SecurityContext> jwkSource = httpSecurity.getSharedObject(JWKSource.class);
if (jwkSource == null) {
ResolvableType type = ResolvableType.forClassWithGenerics(JWKSource.class, SecurityContext.class);
jwkSource = getOptionalBean(httpSecurity, type);
if (jwkSource != null) {
httpSecurity.setSharedObject(JWKSource.class, jwkSource);
}
}
return jwkSource;
}
private static OAuth2TokenCustomizer<JwtEncodingContext> getJwtCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
return getOptionalBean(httpSecurity, type);
}
private static OAuth2TokenCustomizer<OAuth2TokenClaimsContext> getAccessTokenCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, OAuth2TokenClaimsContext.class);
return getOptionalBean(httpSecurity, type);
}
public static AuthorizationServerSettings getAuthorizationServerSettings(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = httpSecurity.getSharedObject(AuthorizationServerSettings.class);
if (authorizationServerSettings == null) {
authorizationServerSettings = getBean(httpSecurity, AuthorizationServerSettings.class);
httpSecurity.setSharedObject(AuthorizationServerSettings.class, authorizationServerSettings);
}
return authorizationServerSettings;
}
public static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
}
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
public static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
httpSecurity.getSharedObject(ApplicationContext.class), type);
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " +
beansMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
public static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return names.length == 1 ? (T) context.getBean(names[0]) : null;
}
}
@@ -0,0 +1,94 @@
package com.central.oauth.utils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/14
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OAuthEndpointUtils {
public static final String ACCESS_TOKEN_REQUEST_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private OAuthEndpointUtils() {
}
public static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
parameters.add(key, value);
}
}
});
return parameters;
}
public static String getParam(MultiValueMap<String, String> parameters, String paramName) {
String paramValue = parameters.getFirst(paramName);
if (!StringUtils.hasText(paramValue) || parameters.get(paramName).size() != 1) {
OAuthEndpointUtils.throwError(
OAuth2ErrorCodes.INVALID_REQUEST,
paramName,
OAuthEndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
}
return paramValue;
}
public static Map<String, Object> getParametersIfMatchesAuthorizationCodeGrantRequest(HttpServletRequest request, String... exclusions) {
if (!matchesAuthorizationCodeGrantRequest(request)) {
return Collections.emptyMap();
}
MultiValueMap<String, String> multiValueParameters = getParameters(request);
for (String exclusion : exclusions) {
multiValueParameters.remove(exclusion);
}
Map<String, Object> parameters = new HashMap<>();
multiValueParameters.forEach((key, value) ->
parameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0])));
return parameters;
}
public static boolean matchesAuthorizationCodeGrantRequest(HttpServletRequest request) {
return AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals(
request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) &&
request.getParameter(OAuth2ParameterNames.CODE) != null;
}
public static boolean matchesPkceTokenRequest(HttpServletRequest request) {
return matchesAuthorizationCodeGrantRequest(request) &&
request.getParameter(PkceParameterNames.CODE_VERIFIER) != null;
}
public static void throwError(String errorCode, String parameterName, String errorUri) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throw new OAuth2AuthenticationException(error);
}
public static String normalizeUserCode(String userCode) {
Assert.hasText(userCode, "userCode cannot be empty");
StringBuilder sb = new StringBuilder(userCode.toUpperCase().replaceAll("[^A-Z\\d]+", ""));
Assert.isTrue(sb.length() == 8, "userCode must be exactly 8 alpha/numeric characters");
sb.insert(4, '-');
return sb.toString();
}
}
@@ -0,0 +1,25 @@
package com.central.oauth.utils;
/**
* @author zlt
* @version 1.0
* @date 2021/10/22
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class UsernameHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal();
public static String getContext() {
return contextHolder.get();
}
public static void setContext(String username) {
contextHolder.set(username);
}
public static void clearContext() {
contextHolder.remove();
}
}
@@ -33,10 +33,6 @@ knife4j:
swagger-model-name: 认证中心接口文档
zlt:
oauth2:
token:
store:
type: redis
security:
code:
# 忽略验证码的应用编号