feat: uaa改造为Spring Authorization Server
This commit is contained in:
@@ -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) {
|
||||
|
||||
+48
@@ -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;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.central.oauth.exception;
|
||||
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
|
||||
/**
|
||||
* @author: zlt
|
||||
* @date: 2023/11/16
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class CustomOAuth2AuthenticationException extends OAuth2AuthenticationException {
|
||||
public CustomOAuth2AuthenticationException(String msg) {
|
||||
super(new OAuth2Error(msg), msg);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+90
@@ -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();
|
||||
}
|
||||
}
|
||||
+55
@@ -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());
|
||||
}
|
||||
}
|
||||
+138
@@ -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();
|
||||
}
|
||||
+38
@@ -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);
|
||||
}
|
||||
}
|
||||
+67
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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);
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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);
|
||||
}
|
||||
}
|
||||
+71
@@ -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;
|
||||
}
|
||||
}
|
||||
+41
@@ -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);
|
||||
}
|
||||
}
|
||||
+81
@@ -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:
|
||||
# 忽略验证码的应用编号
|
||||
|
||||
Reference in New Issue
Block a user