init project v1.0.0
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.oauth.service.impl.RedisClientDetailsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
||||
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
|
||||
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* OAuth2 授权服务器配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/24
|
||||
*/
|
||||
@Configuration
|
||||
@EnableAuthorizationServer
|
||||
@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
|
||||
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
|
||||
/**
|
||||
* 注入authenticationManager 来支持 password grant type
|
||||
*/
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Resource
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private TokenStore tokenStore;
|
||||
|
||||
@Autowired(required = false)
|
||||
private JwtAccessTokenConverter jwtAccessTokenConverter;
|
||||
|
||||
@Autowired(required = false)
|
||||
private TokenEnhancer tokenEnhancer;
|
||||
|
||||
@Autowired
|
||||
private WebResponseExceptionTranslator webResponseExceptionTranslator;
|
||||
|
||||
@Autowired
|
||||
private RedisClientDetailsService clientDetailsService;
|
||||
|
||||
@Autowired
|
||||
private RandomValueAuthorizationCodeServices authorizationCodeServices;
|
||||
|
||||
/**
|
||||
* 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
|
||||
* @param endpoints
|
||||
*/
|
||||
@Override
|
||||
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
|
||||
if (jwtAccessTokenConverter != null) {
|
||||
if (tokenEnhancer != null) {
|
||||
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
|
||||
tokenEnhancerChain.setTokenEnhancers(
|
||||
Arrays.asList(tokenEnhancer, jwtAccessTokenConverter));
|
||||
endpoints.tokenEnhancer(tokenEnhancerChain);
|
||||
} else {
|
||||
endpoints.accessTokenConverter(jwtAccessTokenConverter);
|
||||
}
|
||||
}
|
||||
endpoints.tokenStore(tokenStore)
|
||||
.authenticationManager(authenticationManager)
|
||||
.userDetailsService(userDetailsService)
|
||||
.authorizationCodeServices(authorizationCodeServices)
|
||||
.exceptionTranslator(webResponseExceptionTranslator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置应用名称 应用id
|
||||
* 配置OAuth2的客户端相关信息
|
||||
* @param clients
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
|
||||
clients.withClientDetails(clientDetailsService);
|
||||
clientDetailsService.loadAllClientToCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
|
||||
* @param security
|
||||
*/
|
||||
@Override
|
||||
public void configure(AuthorizationServerSecurityConfigurer security) {
|
||||
security
|
||||
.tokenKeyAccess("isAuthenticated()")
|
||||
.checkTokenAccess("permitAll()")
|
||||
//让/oauth/token支持client_id以及client_secret作登录认证
|
||||
.allowFormAuthenticationForClients();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.oauth.service.impl.RedisAuthorizationCodeServices;
|
||||
import com.central.oauth.service.impl.RedisClientDetailsService;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/12
|
||||
*/
|
||||
@Configuration
|
||||
public class ClientDetailsConfig {
|
||||
@Resource
|
||||
private DataSource dataSource;
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
/**
|
||||
* 声明 ClientDetails实现
|
||||
*/
|
||||
@Bean
|
||||
public RedisClientDetailsService clientDetailsService() {
|
||||
RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource);
|
||||
clientDetailsService.setRedisTemplate(redisTemplate);
|
||||
return clientDetailsService;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RandomValueAuthorizationCodeServices authorizationCodeServices() {
|
||||
RedisAuthorizationCodeServices redisAuthorizationCodeServices = new RedisAuthorizationCodeServices();
|
||||
redisAuthorizationCodeServices.setRedisTemplate(redisTemplate);
|
||||
return redisAuthorizationCodeServices;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
/**
|
||||
* 跨域配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/8/9 15:59
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsConfigration {
|
||||
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
// #允许向该服务器提交请求的URI,*表示全部允许
|
||||
config.addAllowedOrigin(CorsConfiguration.ALL);
|
||||
// 允许cookies跨域
|
||||
config.setAllowCredentials(true);
|
||||
// #允许访问的头信息,*表示全部
|
||||
config.addAllowedHeader(CorsConfiguration.ALL);
|
||||
// 允许提交请求的方法,*表示全部允许
|
||||
config.addAllowedMethod(CorsConfiguration.ALL);
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置过滤器
|
||||
*/
|
||||
@Bean
|
||||
public FilterRegistrationBean someFilterRegistration() {
|
||||
FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
|
||||
registration.setFilter(corsFilter());
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("corsFilter");
|
||||
registration.setOrder(Integer.MIN_VALUE);
|
||||
return registration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.google.code.kaptcha.impl.DefaultKaptcha;
|
||||
import com.google.code.kaptcha.util.Config;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018-12-21 21:12:18
|
||||
*/
|
||||
@Configuration
|
||||
public class KaptchaConfig {
|
||||
private static final String KAPTCHA_BORDER = "kaptcha.border";
|
||||
private static final String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";
|
||||
private static final String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";
|
||||
private static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";
|
||||
private static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
|
||||
private static final String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";
|
||||
private static final Object KAPTCHA_IMAGE_FONT_SIZE = "kaptcha.textproducer.font.size";
|
||||
|
||||
@Bean
|
||||
public DefaultKaptcha producer() {
|
||||
Properties properties = new Properties();
|
||||
properties.put(KAPTCHA_BORDER, SecurityConstants.DEFAULT_IMAGE_BORDER);
|
||||
properties.put(KAPTCHA_TEXTPRODUCER_FONT_COLOR, SecurityConstants.DEFAULT_COLOR_FONT);
|
||||
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, SecurityConstants.DEFAULT_CHAR_SPACE);
|
||||
properties.put(KAPTCHA_IMAGE_WIDTH, SecurityConstants.DEFAULT_IMAGE_WIDTH);
|
||||
properties.put(KAPTCHA_IMAGE_HEIGHT, SecurityConstants.DEFAULT_IMAGE_HEIGHT);
|
||||
properties.put(KAPTCHA_IMAGE_FONT_SIZE, SecurityConstants.DEFAULT_IMAGE_FONT_SIZE);
|
||||
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, SecurityConstants.DEFAULT_IMAGE_LENGTH);
|
||||
Config config = new Config(properties);
|
||||
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
|
||||
defaultKaptcha.setConfig(config);
|
||||
return defaultKaptcha;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.db.config.DefaultMybatisPlusConfig;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/10
|
||||
*/
|
||||
@Configuration
|
||||
@MapperScan({"com.central.oauth.mapper*"})
|
||||
public class MybatisPlusConfig extends DefaultMybatisPlusConfig {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.oauth2.common.config.TokenStoreConfig;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
||||
|
||||
/**
|
||||
* 资源服务器配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/27
|
||||
*/
|
||||
@Configuration
|
||||
@EnableResourceServer
|
||||
@Import(TokenStoreConfig.class)
|
||||
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
|
||||
http.headers().frameOptions().disable()
|
||||
.and()
|
||||
.requestMatcher(request -> false)
|
||||
.authorizeRequests()
|
||||
.antMatchers(securityProperties.getIgnore().getUrls()).permitAll()
|
||||
.anyRequest()
|
||||
.authenticated();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.oauth.mobile.MobileAuthenticationSecurityConfig;
|
||||
import com.central.oauth.openid.OpenIdAuthenticationSecurityConfig;
|
||||
import com.central.common.config.DefaultPasswordConfig;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* spring security配置
|
||||
* 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(SecurityProperties.class)
|
||||
@Import(DefaultPasswordConfig.class)
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private AuthenticationSuccessHandler authenticationSuccessHandler;
|
||||
@Autowired
|
||||
private AuthenticationFailureHandler authenticationFailureHandler;
|
||||
|
||||
@Autowired(required = false)
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Resource
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Resource
|
||||
private LogoutHandler oauthLogoutHandler;
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
@Autowired
|
||||
private ValidateCodeSecurityConfig validateCodeSecurityConfig;
|
||||
|
||||
@Autowired
|
||||
private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;
|
||||
|
||||
@Autowired
|
||||
private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;
|
||||
|
||||
/**
|
||||
* 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
|
||||
* @return 认证管理对象
|
||||
*/
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers( securityProperties.getIgnore().getUrls())
|
||||
.permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage(SecurityConstants.LOGIN_PAGE)
|
||||
.loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
|
||||
.successHandler(authenticationSuccessHandler)
|
||||
.failureHandler(authenticationFailureHandler)
|
||||
.and()
|
||||
.logout()
|
||||
.logoutSuccessUrl(SecurityConstants.LOGIN_PAGE)
|
||||
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
|
||||
.addLogoutHandler(oauthLogoutHandler)
|
||||
.clearAuthentication(true)
|
||||
.and()
|
||||
.apply(validateCodeSecurityConfig)
|
||||
.and()
|
||||
.apply(openIdAuthenticationSecurityConfig)
|
||||
.and()
|
||||
.apply(mobileAuthenticationSecurityConfig)
|
||||
.and()
|
||||
.csrf().disable()
|
||||
// 解决不允许显示在iframe的问题
|
||||
.headers().frameOptions().disable().cacheControl();
|
||||
|
||||
// 基于密码 等模式可以无session,不支持授权码模式
|
||||
if (authenticationEntryPoint != null) {
|
||||
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
|
||||
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
|
||||
} else {
|
||||
// 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证
|
||||
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局用户信息
|
||||
*/
|
||||
@Autowired
|
||||
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.central.oauth.config;
|
||||
|
||||
import com.central.common.utils.ResponseUtil;
|
||||
import com.central.oauth.handler.OauthLogoutHandler;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.common.exceptions.*;
|
||||
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
|
||||
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 认证错误处理
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class SecurityHandlerConfig {
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 登陆失败,返回401
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationFailureHandler loginFailureHandler() {
|
||||
return (request, response, exception) -> {
|
||||
String msg;
|
||||
if (exception instanceof BadCredentialsException) {
|
||||
msg = "密码错误";
|
||||
} else {
|
||||
msg = exception.getMessage();
|
||||
}
|
||||
ResponseUtil.responseWriter(objectMapper, response, msg, HttpStatus.UNAUTHORIZED.value());
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OauthLogoutHandler oauthLogoutHandler() {
|
||||
return new OauthLogoutHandler();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebResponseExceptionTranslator webResponseExceptionTranslator() {
|
||||
return new DefaultWebResponseExceptionTranslator() {
|
||||
public static final String BAD_MSG = "坏的凭证";
|
||||
|
||||
@Override
|
||||
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
|
||||
OAuth2Exception oAuth2Exception;
|
||||
if (e.getMessage() != null && e.getMessage().equals(BAD_MSG)) {
|
||||
oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
|
||||
} else if (e instanceof InternalAuthenticationServiceException) {
|
||||
oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
|
||||
} else if (e instanceof RedirectMismatchException) {
|
||||
oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
|
||||
} else if (e instanceof InvalidScopeException) {
|
||||
oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
|
||||
} else {
|
||||
oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
|
||||
}
|
||||
ResponseEntity<OAuth2Exception> response = super.translate(oAuth2Exception);
|
||||
ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
|
||||
response.getBody().addAdditionalInformation("resp_code", oAuth2Exception.getHttpErrorCode() + "");
|
||||
response.getBody().addAdditionalInformation("resp_msg", oAuth2Exception.getMessage());
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 登陆成功
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationSuccessHandler loginSuccessHandler() {
|
||||
return new SavedRequestAwareAuthenticationSuccessHandler() {
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication authentication) throws IOException, ServletException {
|
||||
super.onAuthenticationSuccess(request, response, authentication);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.central.oauth.config;
|
||||
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.Filter;
|
||||
|
||||
/**
|
||||
* 校验码相关安全配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Component("validateCodeSecurityConfig")
|
||||
public class ValidateCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
@Resource
|
||||
private Filter validateCodeFilter;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) {
|
||||
http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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.google.common.collect.Maps;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 角色相关接口
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Api(tags = "应用")
|
||||
@RestController
|
||||
@RequestMapping("/clients")
|
||||
public class ClientController {
|
||||
@Autowired
|
||||
private IClientService clientService;
|
||||
|
||||
@GetMapping
|
||||
@ApiOperation(value = "应用列表")
|
||||
public PageResult<Client> list(@RequestParam Map<String, Object> params) {
|
||||
return clientService.listClent(params, true);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@ApiOperation(value = "根据id获取应用")
|
||||
public Client get(@PathVariable Long id) {
|
||||
return clientService.getById(id);
|
||||
}
|
||||
|
||||
@GetMapping("/all")
|
||||
@ApiOperation(value = "所有应用")
|
||||
public List<Client> allClient() {
|
||||
PageResult<Client> page = clientService.listClent(Maps.newHashMap(), false);
|
||||
return page.getData();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@ApiOperation(value = "删除应用")
|
||||
public void delete(@PathVariable Long id) {
|
||||
clientService.delClient(id);
|
||||
}
|
||||
|
||||
@PostMapping("/saveOrUpdate")
|
||||
@ApiOperation(value = "保存或者修改应用")
|
||||
public Result saveOrUpdate(@RequestBody ClientDto clientDto) {
|
||||
return clientService.saveClient(clientDto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.central.oauth.controller;
|
||||
|
||||
import com.central.common.annotation.LoginUser;
|
||||
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.model.SysUser;
|
||||
import com.central.common.utils.SpringUtil;
|
||||
import com.central.oauth.mobile.MobileAuthenticationToken;
|
||||
import com.central.oauth.openid.OpenIdAuthenticationToken;
|
||||
import com.central.oauth.service.impl.RedisClientDetailsService;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections.MapUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.*;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.TokenRequest;
|
||||
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OAuth2相关操作
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Api(tags = "OAuth2相关操作")
|
||||
@Slf4j
|
||||
@RestController
|
||||
public class OAuth2Controller {
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Resource
|
||||
private AuthorizationServerTokenServices authorizationServerTokenServices;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
@Value("${test2:}")
|
||||
private String test2;
|
||||
|
||||
@GetMapping("/oauth/test")
|
||||
public String[] testNacos() {
|
||||
return securityProperties.getCode().getIgnoreClientCode();
|
||||
}
|
||||
@GetMapping("/oauth/test2")
|
||||
public String test2() {
|
||||
return test2;
|
||||
}
|
||||
|
||||
@ApiOperation(value = "用户名密码获取token")
|
||||
@PostMapping(SecurityConstants.PASSWORD_LOGIN_PRO_URL)
|
||||
public void getUserTokenInfo(
|
||||
@ApiParam(required = true, name = "username", value = "账号") String username,
|
||||
@ApiParam(required = true, name = "password", value = "密码") String password,
|
||||
HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
|
||||
writerToken(request, response, token, "用户名或密码错误");
|
||||
}
|
||||
|
||||
@ApiOperation(value = "openId获取token")
|
||||
@PostMapping(SecurityConstants.OPENID_TOKEN_URL)
|
||||
public void getTokenByOpenId(
|
||||
@ApiParam(required = true, name = "openId", value = "openId") String openId,
|
||||
HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
OpenIdAuthenticationToken token = new OpenIdAuthenticationToken(openId);
|
||||
writerToken(request, response, token, "openId错误");
|
||||
}
|
||||
|
||||
@ApiOperation(value = "mobile获取token")
|
||||
@PostMapping(SecurityConstants.MOBILE_TOKEN_URL)
|
||||
public void getTokenByMobile(
|
||||
@ApiParam(required = true, name = "mobile", value = "mobile") String mobile,
|
||||
@ApiParam(required = true, name = "password", value = "密码") String password,
|
||||
HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
MobileAuthenticationToken token = new MobileAuthenticationToken(mobile, password);
|
||||
writerToken(request, response, token, "手机号或密码错误");
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前登陆用户信息
|
||||
* security获取当前登录用户的方法是SecurityContextHolder.getContext().getAuthentication()
|
||||
* 这里的实现类是org.springframework.security.oauth2.provider.OAuth2Authentication
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@ApiOperation(value = "当前登陆用户信息")
|
||||
@RequestMapping(value = {"/oauth/userinfo"}, produces = "application/json") // 获取用户信息。/auth/user
|
||||
public Map<String, Object> getCurrentUserDetail(@LoginUser SysUser user) {
|
||||
Map<String, Object> userInfo = new HashMap<>();
|
||||
if (user != null) {
|
||||
LoginAppUser loginAppUser = userService.findByUsername(user.getUsername());
|
||||
userInfo.put("user", loginAppUser);
|
||||
userInfo.put("permissions", loginAppUser.getPermissions());
|
||||
userInfo.put("resp_code", "200");
|
||||
}
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
private void writerToken(HttpServletRequest request, HttpServletResponse response, AbstractAuthenticationToken token
|
||||
, String badCredenbtialsMsg) throws IOException {
|
||||
try {
|
||||
final String[] clientInfos = AuthUtils.extractClient(request);
|
||||
String clientId = clientInfos[0];
|
||||
String clientSecret = clientInfos[1];
|
||||
|
||||
ClientDetails clientDetails = getClient(clientId, clientSecret, null);
|
||||
TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "customer");
|
||||
OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
|
||||
Authentication authentication = authenticationManager.authenticate(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
|
||||
OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
|
||||
oAuth2Authentication.setAuthenticated(true);
|
||||
writerObj(response, oAuth2AccessToken);
|
||||
} catch (BadCredentialsException | InternalAuthenticationServiceException e) {
|
||||
exceptionHandler(response, badCredenbtialsMsg);
|
||||
} catch (Exception e) {
|
||||
exceptionHandler(response, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void exceptionHandler(HttpServletResponse response, Exception e) throws IOException {
|
||||
log.error("exceptionHandler-error:", e);
|
||||
exceptionHandler(response, e.getMessage());
|
||||
}
|
||||
|
||||
private void exceptionHandler(HttpServletResponse response, String msg) throws IOException {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
writerObj(response, Result.failed(msg));
|
||||
}
|
||||
|
||||
private void writerObj(HttpServletResponse response, Object obj) throws IOException {
|
||||
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
try (
|
||||
Writer writer = response.getWriter()
|
||||
) {
|
||||
writer.write(objectMapper.writeValueAsString(obj));
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private ClientDetails getClient(String clientId, String clientSecret, RedisClientDetailsService clientDetailsService) {
|
||||
if (clientDetailsService == null) {
|
||||
clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class);
|
||||
}
|
||||
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
|
||||
|
||||
if (clientDetails == null) {
|
||||
throw new UnapprovedClientAuthenticationException("clientId对应的信息不存在");
|
||||
} else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
|
||||
throw new UnapprovedClientAuthenticationException("clientSecret不匹配");
|
||||
}
|
||||
return clientDetails;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.central.oauth.controller;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.oauth.service.IValidateCodeService;
|
||||
import com.google.code.kaptcha.Producer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
/**
|
||||
* 验证码提供
|
||||
* @author zlt
|
||||
* @date 2018/12/18
|
||||
*/
|
||||
@Controller
|
||||
public class ValidateCodeController {
|
||||
@Autowired
|
||||
private Producer producer;
|
||||
|
||||
@Autowired
|
||||
private IValidateCodeService validateCodeService;
|
||||
|
||||
/**
|
||||
* 创建验证码
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}")
|
||||
public void createCode(@PathVariable String deviceId, HttpServletResponse response)
|
||||
throws Exception {
|
||||
Assert.notNull(deviceId, "机器码不能为空");
|
||||
response.setHeader("Cache-Control", "no-store, no-cache");
|
||||
response.setContentType("image/jpeg");
|
||||
//生成文字验证码
|
||||
String text = producer.createText();
|
||||
//生成图片验证码
|
||||
BufferedImage image = producer.createImage(text);
|
||||
validateCodeService.saveImageCode(deviceId, text);
|
||||
try (
|
||||
ServletOutputStream out = response.getOutputStream()
|
||||
) {
|
||||
ImageIO.write(image, "JPEG", out);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送手机验证码
|
||||
* 后期要加接口限制
|
||||
*
|
||||
* @param mobile 手机号
|
||||
* @return R
|
||||
*/
|
||||
@ResponseBody
|
||||
@GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
|
||||
public Result createCode(@PathVariable String mobile) {
|
||||
Assert.notNull(mobile, "手机号不能为空");
|
||||
return validateCodeService.sendSmsCode(mobile);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
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,81 @@
|
||||
package com.central.oauth.filter;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.oauth.exception.ValidateCodeException;
|
||||
import com.central.oauth.service.IValidateCodeService;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/11/21
|
||||
*/
|
||||
@Slf4j
|
||||
@Component("validateCodeFilter")
|
||||
public class ValidateCodeFilter extends OncePerRequestFilter {
|
||||
@Autowired
|
||||
private IValidateCodeService validateCodeService;
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
/**
|
||||
* 验证码校验失败处理器
|
||||
*/
|
||||
@Autowired
|
||||
private AuthenticationFailureHandler authenticationFailureHandler;
|
||||
|
||||
/**
|
||||
* 验证请求url与配置的url是否匹配的工具类
|
||||
*/
|
||||
private AntPathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
/**
|
||||
* 返回true代表不执行过滤器,false代表执行
|
||||
*/
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
//登录提交的时候验证验证码
|
||||
if (pathMatcher.match(SecurityConstants.PASSWORD_LOGIN_PRO_URL, request.getRequestURI())) {
|
||||
//判断是否有不验证验证码的client
|
||||
if (securityProperties.getCode().getIgnoreClientCode().length > 0) {
|
||||
try {
|
||||
final String[] clientInfos = AuthUtils.extractClient(request);
|
||||
String clientId = clientInfos[0];
|
||||
for (String client : securityProperties.getCode().getIgnoreClientCode()) {
|
||||
if (client.equals(clientId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("解析client信息失败", e);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
try {
|
||||
validateCodeService.validate(request);
|
||||
} catch (ValidateCodeException e) {
|
||||
authenticationFailureHandler.onAuthenticationFailure(request, response, e);
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.central.oauth.handler;
|
||||
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/10/17
|
||||
*/
|
||||
@Slf4j
|
||||
public class OauthLogoutHandler implements LogoutHandler {
|
||||
@Autowired
|
||||
private TokenStore tokenStore;
|
||||
|
||||
@Override
|
||||
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
|
||||
Assert.notNull(tokenStore, "tokenStore must be set");
|
||||
String token = AuthUtils.extractToken(request);
|
||||
if(StringUtils.isNotBlank(token)){
|
||||
OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
|
||||
OAuth2RefreshToken refreshToken;
|
||||
if (existingAccessToken != null) {
|
||||
if (existingAccessToken.getRefreshToken() != null) {
|
||||
log.info("remove refreshToken!", existingAccessToken.getRefreshToken());
|
||||
refreshToken = existingAccessToken.getRefreshToken();
|
||||
tokenStore.removeRefreshToken(refreshToken);
|
||||
}
|
||||
log.info("remove existingAccessToken!", existingAccessToken);
|
||||
tokenStore.removeAccessToken(existingAccessToken);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.db.mapper.SuperMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import com.central.oauth.model.Client;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public interface ClientMapper extends SuperMapper<Client> {
|
||||
//int count(@Param("params") Map<String, Object> params);
|
||||
|
||||
List<Client> findList(Page<Client> page, @Param("params") Map<String, Object> params );
|
||||
|
||||
/*@Select("select * from oauth_client_details t where t.client_id = #{clientId}")
|
||||
Client getClient(String clientId);*/
|
||||
|
||||
/*@Update("update oauth_client_details t set t.client_secret = #{clientSecret},t.client_secret_str = #{clientSecretStr} where t.id = #{id}")
|
||||
int update(Client client);*/
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.central.oauth.mobile;
|
||||
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import lombok.Setter;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
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;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
public class MobileAuthenticationProvider implements AuthenticationProvider {
|
||||
private ZltUserDetailsService userDetailsService;
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
|
||||
String mobile = (String) authenticationToken.getPrincipal();
|
||||
String password = (String) authenticationToken.getCredentials();
|
||||
UserDetails user = userDetailsService.loadUserByMobile(mobile);
|
||||
if (user == null) {
|
||||
throw new InternalAuthenticationServiceException("手机号或密码错误");
|
||||
}
|
||||
if (!passwordEncoder.matches(password, user.getPassword())) {
|
||||
throw new BadCredentialsException("手机号或密码错误");
|
||||
}
|
||||
MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, password, user.getAuthorities());
|
||||
authenticationResult.setDetails(authenticationToken.getDetails());
|
||||
return authenticationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return MobileAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.central.oauth.mobile;
|
||||
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* mobile的相关处理配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Component
|
||||
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
@Autowired
|
||||
private ZltUserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) {
|
||||
//mobile provider
|
||||
MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder);
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.central.oauth.mobile;
|
||||
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.SpringSecurityCoreVersion;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private final Object principal;
|
||||
private Object credentials;
|
||||
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
/**
|
||||
* This constructor can be safely used by any code that wishes to create a
|
||||
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
|
||||
* will return <code>false</code>.
|
||||
*
|
||||
*/
|
||||
public MobileAuthenticationToken(String mobile, String password) {
|
||||
super(null);
|
||||
this.principal = mobile;
|
||||
this.credentials = password;
|
||||
setAuthenticated(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor should only be used by <code>AuthenticationManager</code> or
|
||||
* <code>AuthenticationProvider</code> implementations that are satisfied with
|
||||
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
|
||||
* authentication token.
|
||||
*
|
||||
* @param principal
|
||||
* @param authorities
|
||||
*/
|
||||
public MobileAuthenticationToken(Object principal, Object credentials,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(authorities);
|
||||
this.principal = principal;
|
||||
this.credentials = credentials;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return this.credentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return this.principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
if (isAuthenticated) {
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
|
||||
}
|
||||
super.setAuthenticated(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eraseCredentials() {
|
||||
super.eraseCredentials();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.central.oauth.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.central.common.model.SuperEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("oauth_client_details")
|
||||
public class Client extends SuperEntity {
|
||||
private static final long serialVersionUID = -8185413579135897885L;
|
||||
private String clientId;
|
||||
private String resourceIds = "";
|
||||
private String clientSecret;
|
||||
private String clientSecretStr;
|
||||
private String scope = "all";
|
||||
private String authorizedGrantTypes = "authorization_code,password,refresh_token,client_credentials";
|
||||
private String webServerRedirectUri;
|
||||
private String authorities = "";
|
||||
private Integer accessTokenValidity = 18000;
|
||||
private Integer refreshTokenValidity = 28800;
|
||||
private String additionalInformation = "{}";
|
||||
private String autoapprove = "true";
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.central.oauth.openid;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.social.security.SocialUserDetailsService;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class OpenIdAuthenticationProvider implements AuthenticationProvider {
|
||||
|
||||
private SocialUserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
|
||||
String openId = (String) authenticationToken.getPrincipal();
|
||||
UserDetails user = userDetailsService.loadUserByUserId(openId);
|
||||
if (user == null) {
|
||||
throw new InternalAuthenticationServiceException("openId错误");
|
||||
}
|
||||
OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(user, user.getAuthorities());
|
||||
authenticationResult.setDetails(authenticationToken.getDetails());
|
||||
return authenticationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
|
||||
public SocialUserDetailsService getUserDetailsService() {
|
||||
return userDetailsService;
|
||||
}
|
||||
|
||||
public void setUserDetailsService(SocialUserDetailsService userDetailsService) {
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.central.oauth.openid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.social.security.SocialUserDetailsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* openId的相关处理配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Component
|
||||
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
@Autowired
|
||||
private SocialUserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) {
|
||||
//openId provider
|
||||
OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.central.oauth.openid;
|
||||
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.SpringSecurityCoreVersion;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class OpenIdAuthenticationToken extends AbstractAuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private final Object principal;
|
||||
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
/**
|
||||
* This constructor can be safely used by any code that wishes to create a
|
||||
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
|
||||
* will return <code>false</code>.
|
||||
*
|
||||
*/
|
||||
public OpenIdAuthenticationToken(String openId) {
|
||||
super(null);
|
||||
this.principal = openId;
|
||||
setAuthenticated(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor should only be used by <code>AuthenticationManager</code> or
|
||||
* <code>AuthenticationProvider</code> implementations that are satisfied with
|
||||
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
|
||||
* authentication token.
|
||||
*
|
||||
* @param principal
|
||||
* @param authorities
|
||||
*/
|
||||
public OpenIdAuthenticationToken(Object principal,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(authorities);
|
||||
this.principal = principal;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return this.principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
if (isAuthenticated) {
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
|
||||
}
|
||||
super.setAuthenticated(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eraseCredentials() {
|
||||
super.eraseCredentials();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public interface IClientService extends ISuperService<Client> {
|
||||
Result saveClient(Client clientDto);
|
||||
|
||||
/**
|
||||
* 查询应用列表
|
||||
* @param params
|
||||
* @param isPage 是否分页
|
||||
*/
|
||||
PageResult<Client> listClent(Map<String, Object> params, boolean isPage);
|
||||
|
||||
void delClient(long id);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.central.oauth.service;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/10
|
||||
*/
|
||||
public interface IValidateCodeService {
|
||||
/**
|
||||
* 保存图形验证码
|
||||
* @param deviceId 前端唯一标识
|
||||
* @param imageCode 验证码
|
||||
*/
|
||||
void saveImageCode(String deviceId, String imageCode);
|
||||
|
||||
Result sendSmsCode(String mobile);
|
||||
|
||||
/**
|
||||
* 获取验证码
|
||||
* @param deviceId 前端唯一标识/手机号
|
||||
*/
|
||||
String getCode(String deviceId);
|
||||
|
||||
/**
|
||||
* 删除验证码
|
||||
* @param deviceId 前端唯一标识/手机号
|
||||
*/
|
||||
void remove(String deviceId);
|
||||
|
||||
/**
|
||||
* 验证验证码
|
||||
*/
|
||||
void validate(HttpServletRequest request);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.central.oauth.service;
|
||||
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/28
|
||||
*/
|
||||
public interface ZltUserDetailsService extends UserDetailsService {
|
||||
UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.lock.DistributedLock;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.common.redis.template.RedisRepository;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
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;
|
||||
import com.central.oauth.service.IClientService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> implements IClientService {
|
||||
private final static String LOCK_KEY_CLIENTID = CommonConstant.LOCK_KEY_PREFIX+"clientId:";
|
||||
|
||||
@Autowired
|
||||
private RedisRepository redisRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private DistributedLock lock;
|
||||
|
||||
@Override
|
||||
public Result saveClient(Client client) {
|
||||
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
|
||||
String clientId = client.getClientId();
|
||||
super.saveOrUpdateIdempotency(client, lock
|
||||
, LOCK_KEY_CLIENTID+clientId
|
||||
, new QueryWrapper<Client>().eq("client_id", clientId)
|
||||
, clientId + "已存在");
|
||||
// 写入redis缓存
|
||||
redisRepository.set(clientRedisKey(client.getClientId()), client);
|
||||
return Result.succeed("操作成功");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<Client> listClent(Map<String, Object> params, boolean isPage) {
|
||||
Page<Client> page;
|
||||
if (isPage) {
|
||||
page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
|
||||
} else {
|
||||
page = new Page<>(1, -1);
|
||||
}
|
||||
List<Client> list = baseMapper.findList(page, params);
|
||||
page.setRecords(list);
|
||||
return PageResult.<Client>builder().data(list).code(0).count(page.getTotal()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delClient(long id) {
|
||||
String clientId = baseMapper.selectById(id).getClientId();
|
||||
baseMapper.deleteById(id);
|
||||
redisRepository.del(clientRedisKey(clientId));
|
||||
}
|
||||
|
||||
private String clientRedisKey(String clientId) {
|
||||
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* JdbcAuthorizationCodeServices替换
|
||||
*/
|
||||
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
|
||||
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
public RedisTemplate<String, Object> getRedisTemplate() {
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换JdbcAuthorizationCodeServices的存储策略
|
||||
* 将存储code到redis,并设置过期时间,10分钟
|
||||
*/
|
||||
@Override
|
||||
protected void store(String code, OAuth2Authentication authentication) {
|
||||
redisTemplate.opsForValue().set(redisKey(code), authentication, 10, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected OAuth2Authentication remove(final String code) {
|
||||
String codeKey = redisKey(code);
|
||||
OAuth2Authentication token = (OAuth2Authentication) redisTemplate.opsForValue().get(codeKey);
|
||||
this.redisTemplate.delete(codeKey);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* redis中 code key的前缀
|
||||
*
|
||||
* @param code
|
||||
* @return
|
||||
*/
|
||||
private String redisKey(String code) {
|
||||
return "oauth:code:" + code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.NoSuchClientException;
|
||||
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @version 创建时间:2017年11月12日 上午22:57:51
|
||||
* 类说明
|
||||
* 将oauth_client_details表数据缓存到redis,这里做个缓存优化
|
||||
* layui模块中有对oauth_client_details的crud, 注意同步redis的数据
|
||||
* 注意对oauth_client_details清楚redis db部分数据的清空
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedisClientDetailsService extends JdbcClientDetailsService {
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
public RedisClientDetailsService(DataSource dataSource) {
|
||||
super(dataSource);
|
||||
}
|
||||
|
||||
public RedisTemplate<String, Object> getRedisTemplate() {
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
|
||||
// 先从redis获取
|
||||
ClientDetails clientDetails = (ClientDetails) redisTemplate.opsForValue().get(clientRedisKey(clientId));
|
||||
if (clientDetails == null) {
|
||||
clientDetails = cacheAndGetClient(clientId);
|
||||
}
|
||||
return clientDetails;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存client并返回client
|
||||
* @param clientId
|
||||
* @return
|
||||
*/
|
||||
private ClientDetails cacheAndGetClient(String clientId) {
|
||||
// 从数据库读取
|
||||
ClientDetails clientDetails = null;
|
||||
try {
|
||||
clientDetails = super.loadClientByClientId(clientId);
|
||||
if (clientDetails != null) {
|
||||
// 写入redis缓存
|
||||
redisTemplate.opsForValue().set(clientRedisKey(clientId), clientDetails);
|
||||
log.info("缓存clientId:{},{}", clientId, clientDetails);
|
||||
}
|
||||
} catch (NoSuchClientException e) {
|
||||
log.error("clientId:{},{}", clientId, clientId);
|
||||
} catch (InvalidClientException e) {
|
||||
log.error("cacheAndGetClient-invalidClient:{}", clientId, e);
|
||||
}
|
||||
return clientDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {
|
||||
super.updateClientDetails(clientDetails);
|
||||
cacheAndGetClient(clientDetails.getClientId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {
|
||||
super.updateClientSecret(clientId, secret);
|
||||
cacheAndGetClient(clientId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeClientDetails(String clientId) throws NoSuchClientException {
|
||||
super.removeClientDetails(clientId);
|
||||
removeRedisCache(clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除redis缓存
|
||||
*
|
||||
* @param clientId
|
||||
*/
|
||||
private void removeRedisCache(String clientId) {
|
||||
redisTemplate.opsForValue().get(clientRedisKey(clientId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将oauth_client_details全表刷入redis
|
||||
*/
|
||||
public void loadAllClientToCache() {
|
||||
List<ClientDetails> list = super.listClientDetails();
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
log.error("oauth_client_details表数据为空,请检查");
|
||||
return;
|
||||
}
|
||||
|
||||
list.parallelStream().forEach(client -> {
|
||||
redisTemplate.opsForValue().set(clientRedisKey(client.getClientId()), client);
|
||||
});
|
||||
}
|
||||
|
||||
private String clientRedisKey(String clientId) {
|
||||
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.social.security.SocialUserDetails;
|
||||
import org.springframework.social.security.SocialUserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserDetailServiceImpl implements ZltUserDetailsService, SocialUserDetailsService {
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
LoginAppUser loginAppUser = userService.findByUsername(username);
|
||||
if (loginAppUser == null) {
|
||||
throw new InternalAuthenticationServiceException("用户名或密码错误");
|
||||
}
|
||||
return checkUser(loginAppUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocialUserDetails loadUserByUserId(String openId) throws UsernameNotFoundException {
|
||||
LoginAppUser loginAppUser = userService.findByOpenId(openId);
|
||||
return checkUser(loginAppUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
|
||||
LoginAppUser loginAppUser = userService.findByMobile(mobile);
|
||||
return checkUser(loginAppUser);
|
||||
}
|
||||
|
||||
private LoginAppUser checkUser(LoginAppUser loginAppUser) {
|
||||
if (loginAppUser != null && !loginAppUser.isEnabled()) {
|
||||
throw new DisabledException("用户已作废");
|
||||
}
|
||||
return loginAppUser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.redis.template.RedisRepository;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.oauth.exception.ValidateCodeException;
|
||||
import com.central.oauth.service.IValidateCodeService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.bind.ServletRequestBindingException;
|
||||
import org.springframework.web.bind.ServletRequestUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/10
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ValidateCodeServiceImpl implements IValidateCodeService {
|
||||
@Autowired
|
||||
private RedisRepository redisRepository;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 保存用户验证码,和randomStr绑定
|
||||
*
|
||||
* @param deviceId 客户端生成
|
||||
* @param imageCode 验证码信息
|
||||
*/
|
||||
@Override
|
||||
public void saveImageCode(String deviceId, String imageCode) {
|
||||
redisRepository.setExpire(buildKey(deviceId), imageCode, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送验证码
|
||||
* <p>
|
||||
* 1. 先去redis 查询是否 60S内已经发送
|
||||
* 2. 未发送: 判断手机号是否存 ? false :产生4位数字 手机号-验证码
|
||||
* 3. 发往消息中心-》发送信息
|
||||
* 4. 保存redis
|
||||
*
|
||||
* @param mobile 手机号
|
||||
* @return true、false
|
||||
*/
|
||||
@Override
|
||||
public Result sendSmsCode(String mobile) {
|
||||
Object tempCode = redisRepository.get(buildKey(mobile));
|
||||
if (tempCode != null) {
|
||||
log.error("用户:{}验证码未失效{}", mobile, tempCode);
|
||||
return Result.failed("验证码未失效,请失效后再次申请");
|
||||
}
|
||||
|
||||
SysUser user = userService.findByMobile(mobile);
|
||||
if (user != null) {
|
||||
log.error("根据用户手机号{}查询用户为空", mobile);
|
||||
return Result.failed("手机号不存在");
|
||||
}
|
||||
|
||||
String code = RandomUtil.randomNumbers(4);
|
||||
log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
|
||||
redisRepository.setExpire(buildKey(mobile), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
|
||||
return Result.succeed("true");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取验证码
|
||||
* @param deviceId 前端唯一标识/手机号
|
||||
*/
|
||||
@Override
|
||||
public String getCode(String deviceId) {
|
||||
return (String)redisRepository.get(buildKey(deviceId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除验证码
|
||||
* @param deviceId 前端唯一标识/手机号
|
||||
*/
|
||||
@Override
|
||||
public void remove(String deviceId) {
|
||||
redisRepository.del(buildKey(deviceId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证验证码
|
||||
*/
|
||||
@Override
|
||||
public void validate(HttpServletRequest request) throws ValidateCodeException {
|
||||
String deviceId = request.getParameter("deviceId");
|
||||
if (StringUtils.isBlank(deviceId)) {
|
||||
throw new ValidateCodeException("请在请求参数中携带deviceId参数");
|
||||
}
|
||||
String code = this.getCode(deviceId);
|
||||
String codeInRequest;
|
||||
try {
|
||||
codeInRequest = ServletRequestUtils.getStringParameter(request, "validCode");
|
||||
} catch (ServletRequestBindingException e) {
|
||||
throw new ValidateCodeException("获取验证码的值失败");
|
||||
}
|
||||
if (StringUtils.isBlank(codeInRequest)) {
|
||||
throw new ValidateCodeException("请填写验证码");
|
||||
}
|
||||
|
||||
if (code == null) {
|
||||
throw new ValidateCodeException("验证码不存在或已过期");
|
||||
}
|
||||
|
||||
if (!StringUtils.equals(code, codeInRequest)) {
|
||||
throw new ValidateCodeException("验证码不正确");
|
||||
}
|
||||
|
||||
this.remove(deviceId);
|
||||
}
|
||||
|
||||
private String buildKey(String deviceId) {
|
||||
return SecurityConstants.DEFAULT_CODE_KEY + ":" + deviceId;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user