init project v1.0.0

This commit is contained in:
zlt
2019-01-19 15:31:26 +08:00
parent 5c1cdaa54e
commit 19fecc3b05
728 changed files with 65634 additions and 0 deletions
@@ -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);
}
}