init project v1.0.0
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
package com.central;
|
||||
|
||||
import com.central.common.annotation.EnableLoginArgResolver;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@EnableFeignClients
|
||||
@EnableDiscoveryClient
|
||||
@EnableRedisHttpSession
|
||||
@EnableLoginArgResolver
|
||||
@SpringBootApplication
|
||||
public class UaaServerApp {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UaaServerApp.class, args);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://${zlt.datasource.ip}:3306/oauth-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.jdbc.Driver
|
||||
|
||||
redis:
|
||||
host: ${zlt.redis.host}
|
||||
port: ${zlt.redis.port}
|
||||
timeout: ${zlt.redis.timeout}
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
#实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: com.central.oauth.model
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: auto
|
||||
|
||||
zlt:
|
||||
oauth2:
|
||||
token:
|
||||
store:
|
||||
type: authJwt
|
||||
swagger:
|
||||
enabled: true
|
||||
title: 认证中心
|
||||
description: 认证中心接口文档
|
||||
version: 1.0
|
||||
base-package: com.central.oauth.controller
|
||||
security:
|
||||
ignore:
|
||||
# 忽略认证的地址
|
||||
httpUrls: >
|
||||
/validata/**,
|
||||
/clients,
|
||||
/clients/**,
|
||||
/login.html,
|
||||
/css/**,
|
||||
/images/**,
|
||||
/js/**
|
||||
code:
|
||||
# 忽略验证码的应用编号
|
||||
ignoreClientCode: app
|
||||
@@ -0,0 +1,20 @@
|
||||
server:
|
||||
port: 8000
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: uaa-server
|
||||
cloud:
|
||||
nacos:
|
||||
config:
|
||||
server-addr: ${zlt.nacos.server-addr}
|
||||
file-extension: yml
|
||||
shared-dataids: common.yml
|
||||
discovery:
|
||||
server-addr: ${zlt.nacos.server-addr}
|
||||
|
||||
encrypt:
|
||||
key-store:
|
||||
location: classpath:zlt.jks
|
||||
secret: zlt!@#$
|
||||
alias: zlt
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.central.oauth.mapper.ClientMapper">
|
||||
|
||||
<sql id="where">
|
||||
<where>
|
||||
<if test="params.clientId!= null and params.clientId != ''">
|
||||
and client_id = #{params.clientId}
|
||||
</if>
|
||||
<if test="params.resourceIds != null and params.resourceIds != ''">
|
||||
and resource_ids = #{params.resourceIds}
|
||||
</if>
|
||||
<if test="params.clientSecret != null and params.clientSecret != ''">
|
||||
and client_secret = #{params.clientSecret}
|
||||
</if>
|
||||
<if test="params.scope != null and params.scope != ''">
|
||||
and scope = #{params.scope}
|
||||
</if>
|
||||
<if test="params.authorizedGrantTypes != null and params.authorizedGrantTypes != ''">
|
||||
and authorized_grant_types = #{params.authorizedGrantTypes}
|
||||
</if>
|
||||
<if test="params.webServerRedirectUri != null and params.webServerRedirectUri != ''">
|
||||
and web_server_redirect_uri = #{params.webServerRedirectUri}
|
||||
</if>
|
||||
<if test="params.authorities != null and params.authorities != ''">
|
||||
and authorities = #{params.authorities}
|
||||
</if>
|
||||
<if test="params.accessTokenValidity != null and params.accessTokenValidity != ''">
|
||||
and access_token_validity = #{params.accessTokenValidity}
|
||||
</if>
|
||||
<if test="params.refreshTokenValidity != null and params.refreshTokenValidity != ''">
|
||||
and refresh_token_validity = #{params.refreshTokenValidity}
|
||||
</if>
|
||||
<if test="params.additionalInformation != null and params.additionalInformation != ''">
|
||||
and additional_information = #{params.additionalInformation}
|
||||
</if>
|
||||
<if test="params.autoapprove != null and params.autoapprove != ''">
|
||||
and autoapprove = #{params.autoapprove}
|
||||
</if>
|
||||
<if test="params.searchKey != null and params.searchKey != ''">
|
||||
and client_id like concat('%', #{params.searchKey}, '%')
|
||||
</if>
|
||||
|
||||
</where>
|
||||
</sql>
|
||||
|
||||
<select id="findList" resultType="com.central.oauth.model.Client">
|
||||
select id , client_id , resource_ids ,
|
||||
client_secret ,
|
||||
client_secret_str ,
|
||||
web_server_redirect_uri from oauth_client_details t
|
||||
<include refid="where"/>
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -0,0 +1,9 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjmgfejBXsPYynAIPczHA
|
||||
eEvTDfAVaNKQudyI7VszdezbHDM1CStCIgwiMmLd7QYf1SrrmQoqxhcSRbhjE3ej
|
||||
RF5qzhtx3kmepdpMrQptcsLjRkixaxCc4E2k6Us5707gGwbhoaTrRit5F2MnAdLY
|
||||
C1TS3WwnO/hQfqUcAglbK8yrJ4AwAv0DAoIUSWnWqzuniV1SYbdV57uswxUssoWy
|
||||
sEfPz+nv1ZLRs6Wz4eQ5Myqx2+CjWc9F8iXa2PV8Rmjms3dVbWcLUpCP18Dfzp8l
|
||||
n8vF9LfYB7UaLSpfJe6FFF6+vCg4JHfo12djTUgwGjauMF3e9mmjU83KIoQS66lp
|
||||
AQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,173 @@
|
||||
header{
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
background: #1e1b29;
|
||||
border-bottom: solid 4px red;
|
||||
}
|
||||
.member_wrap{
|
||||
|
||||
}
|
||||
.header_item{
|
||||
overflow: hidden;
|
||||
}
|
||||
.header_item{
|
||||
|
||||
width: 980px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.menu_head{
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border-radius: 100px;
|
||||
border: solid 3px #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
.menu_head img{
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.menu_info{
|
||||
width:840px;
|
||||
margin-left: 20px;
|
||||
}
|
||||
.info_name{
|
||||
font-size: 18px;
|
||||
line-height: 40px;
|
||||
font-weight: bold;
|
||||
color: #fff;
|
||||
}
|
||||
.info_name_box{
|
||||
margin-top: 10px;
|
||||
}
|
||||
.level{
|
||||
font-size: 14px;
|
||||
color: #f60;
|
||||
font-weight: bold;
|
||||
}
|
||||
.info_desc{
|
||||
margin-top: 10px;
|
||||
font-size: 14px;
|
||||
color: #FFF;
|
||||
}
|
||||
.banner_menu{
|
||||
width: 980px;
|
||||
height: 50px;
|
||||
margin: 20px auto;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
|
||||
.nav_box{
|
||||
margin-top: 50px;
|
||||
}
|
||||
.nav_box ul {
|
||||
overflow: hidden;
|
||||
}
|
||||
.nav_box ul li{
|
||||
display: block;
|
||||
padding: 0 20px;
|
||||
}
|
||||
.nav_box ul li a{
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
}
|
||||
.nav_box ul li a:hover{
|
||||
color: red;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.login_wrap{
|
||||
background: url(/api-uaa/images/logo_bg.jpg) no-repeat center;
|
||||
/*background-size: 100%;*/
|
||||
}
|
||||
.logo{
|
||||
width: 500px;
|
||||
height: 150px;
|
||||
margin: 0px auto;
|
||||
background: url(/api-uaa/images/logowz.png) no-repeat center;
|
||||
}
|
||||
.login_box{
|
||||
width: 360px;
|
||||
background: #FFFFFF;
|
||||
margin: 0px auto;
|
||||
}
|
||||
.login_title{
|
||||
font-size: 25px;
|
||||
text-align: center;
|
||||
color: #FF7F50;
|
||||
padding: 15px 0;
|
||||
width: 300px;
|
||||
margin: 0 auto;
|
||||
border-bottom: solid 1px #CCCCCC;
|
||||
}
|
||||
.form_text_ipt{
|
||||
width: 300px;
|
||||
height: 40px;
|
||||
border: solid 1px #CCCCCC;
|
||||
margin: 20px auto 0 auto;
|
||||
background: #FFFFFF;
|
||||
}
|
||||
.form_check_ipt{
|
||||
width: 300px;
|
||||
margin: 10px auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
.form_text_ipt input{
|
||||
width: 290px;
|
||||
height: 30px;
|
||||
margin: 5px;
|
||||
border: none;
|
||||
font-family: "微软雅黑";
|
||||
font-size: 15px;
|
||||
color: #666;
|
||||
}
|
||||
.check_left label{
|
||||
cursor: pointer;
|
||||
}
|
||||
.check_left label input{
|
||||
position: relative;
|
||||
top: 2px;
|
||||
}
|
||||
.form_btn{
|
||||
width: 300px;
|
||||
height: 40px;
|
||||
margin: 10px auto;
|
||||
}
|
||||
.form_btn button{
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
color: #FFFFFF;
|
||||
font-size: 14px;
|
||||
background: #FF7F50;
|
||||
cursor: pointer;
|
||||
}
|
||||
.form_reg_btn{
|
||||
width: 300px;
|
||||
margin: 0 auto;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
}
|
||||
.other_login{
|
||||
overflow: hidden;
|
||||
width: 300px;
|
||||
height: 80px;
|
||||
line-height: 80px;
|
||||
margin: 0px auto;
|
||||
}
|
||||
.other_left{
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.other_right a{
|
||||
margin:5px;
|
||||
color:#636363;
|
||||
}
|
||||
|
||||
.other_right a:hover{
|
||||
color:#AEEEEE;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*reset*/
|
||||
*{padding: 0;margin: 0;}
|
||||
html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, menu, nav, section, time, mark, audio, video, details, summary {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
font-size: 100%;
|
||||
font-weight: normal;
|
||||
vertical-align: baseline;
|
||||
background: transparent;
|
||||
}
|
||||
article, aside, figure, footer, header, nav, section, details, summary {display: block;}
|
||||
html, body { height: 100%; color: #333; font-size: 12px; font-family: "微软雅黑",MicrosoftYaHei;}
|
||||
a { text-decoration: none; color: #3cf; -webkit-tap-highlight-color: transparent;}
|
||||
li{list-style: none;}
|
||||
table{border-collapse: collapse;}
|
||||
input {outline: medium none;font-family: "微软雅黑",MicrosoftYaHei;font-size: 14px;}
|
||||
button{font-family:"微软雅黑",MicrosoftYaHei;}
|
||||
em {font-style: normal;}
|
||||
.wrap{max-width: 100%;min-height: 100%;overflow: hidden;margin: 0 auto;background: #ccc;}
|
||||
|
||||
.left{float: left;}
|
||||
.right{float: right;}
|
||||
.clear{clear:both;}
|
||||
.red{color: #f60;}
|
||||
|
||||
.ececk_warning{
|
||||
font-size: 13px;
|
||||
color: red;
|
||||
width: 300px;
|
||||
margin: 0 auto;
|
||||
display: none;
|
||||
}
|
||||
._warning{
|
||||
font-size: 13px;
|
||||
color: red;
|
||||
width: 300px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 331 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.8 KiB |
@@ -0,0 +1,37 @@
|
||||
$(function(){
|
||||
|
||||
//
|
||||
$('.form_text_ipt input').focus(function(){
|
||||
$(this).parent().css({
|
||||
'box-shadow':'0 0 3px #bbb',
|
||||
});
|
||||
});
|
||||
$('.form_text_ipt input').blur(function(){
|
||||
$(this).parent().css({
|
||||
'box-shadow':'none',
|
||||
});
|
||||
//$(this).parent().next().hide();
|
||||
});
|
||||
|
||||
//
|
||||
$('.form_text_ipt input').bind('input propertychange',function(){
|
||||
if($(this).val()==""){
|
||||
$(this).css({
|
||||
'color':'red',
|
||||
});
|
||||
$(this).parent().css({
|
||||
'border':'solid 1px red',
|
||||
});
|
||||
//$(this).parent().next().find('span').html('helow');
|
||||
$(this).parent().next().show();
|
||||
}else{
|
||||
$(this).css({
|
||||
'color':'#ccc',
|
||||
});
|
||||
$(this).parent().css({
|
||||
'border':'solid 1px #ccc',
|
||||
});
|
||||
$(this).parent().next().hide();
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,45 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>登录界面</title>
|
||||
<link rel="stylesheet" href="/api-uaa/css/reset.css"/>
|
||||
<link rel="stylesheet" href="/api-uaa/css/common.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap login_wrap">
|
||||
<div class="content">
|
||||
<div class="logo"></div>
|
||||
<div class="login_box">
|
||||
|
||||
<div class="login_form">
|
||||
<div class="login_title">
|
||||
登录
|
||||
</div>
|
||||
<form action="/user/login" method="post">
|
||||
<div class="form_text_ipt">
|
||||
<input name="username" type="text" placeholder="用户名" value="admin">
|
||||
</div>
|
||||
<div class="ececk_warning"><span>用户名不能为空</span></div>
|
||||
<div class="_warning"><span></span></div>
|
||||
<div class="form_text_ipt">
|
||||
<input name="password" type="password" placeholder="密码" value="admin">
|
||||
</div>
|
||||
<div class="ececk_warning"><span>密码不能为空</span></div>
|
||||
<div class="form_btn">
|
||||
<button type="submit">登录</button>
|
||||
</div>
|
||||
<div class="form_reg_btn">
|
||||
<!--span>还没有帐号?</span><a href="/register">马上注册</a-->
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript" src="/api-uaa/js/jquery.min.js"></script>
|
||||
<script type="text/javascript" src="/api-uaa/js/common.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
Reference in New Issue
Block a user