Browse Source

bug修改

chenweida 7 năm trước cách đây
mục cha
commit
96914c97e3
31 tập tin đã thay đổi với 649 bổ sung87 xóa
  1. 16 0
      base/common-security/pom.xml
  2. 18 12
      base/common-security/readme.MD
  3. 7 12
      base/common-security/src/main/java/com.yihu.base.security/config/AuthorizationServerConfig.java
  4. 3 1
      base/common-security/src/main/java/com.yihu.base.security/config/ResourceServerConfig.java
  5. 19 2
      base/common-security/src/main/java/com.yihu.base.security/hander/BaseAuthenticationSuccessHandler.java
  6. 21 0
      base/common-security/src/main/java/com.yihu.base.security/properties/QQProperties.java
  7. 1 1
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationFilter.java
  8. 1 1
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationProvider.java
  9. 32 28
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationSecurityConfig.java
  10. 1 1
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationToken.java
  11. 1 1
      base/common-security/src/main/java/com.yihu.base.security/sms/controller/SmsController.java
  12. 3 3
      base/common-security/src/main/java/com.yihu.base.security/sms/filter/SmsvalidateCodeFilter.java
  13. 2 2
      base/common-security/src/main/java/com.yihu.base.security/sms/mobile/DefaultMobileCheck.java
  14. 8 10
      base/common-security/src/main/java/com.yihu.base.security/sms/process/SmsValidateCodeProcessor.java
  15. 0 3
      base/common-security/src/main/java/com.yihu.base.security/sms/sender/DefaultSmsCodeSender.java
  16. 1 1
      base/common-security/src/main/java/com.yihu.base.security/sms/vo/ValidateCode.java
  17. 13 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQ.java
  18. 60 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQImpl.java
  19. 206 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQUserInfo.java
  20. 36 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/config/QQAutoConfig.java
  21. 43 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQAdapter.java
  22. 18 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQConnectionFactory.java
  23. 51 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQOAuth2Template.java
  24. 32 0
      base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQServiceProvider.java
  25. 1 1
      base/common-security/src/main/resources/template.yml
  26. 26 3
      svr-lib-parent-pom/pom.xml
  27. 7 1
      svr/svr-demo/src/main/java/com/yihu/jw/model/SaasDO.java
  28. 9 1
      svr/svr-demo/src/main/java/com/yihu/jw/service/ClientService.java
  29. 2 1
      svr/svr-demo/src/main/java/com/yihu/jw/service/RbasService.java
  30. 9 0
      svr/svr-demo/src/main/java/com/yihu/jw/service/UserService.java
  31. 2 2
      svr/svr-demo/src/main/resources/application.yml

+ 16 - 0
base/common-security/pom.xml

@ -78,6 +78,22 @@
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-web</artifactId>
        </dependency>
    </dependencies>
</project>

+ 18 - 12
base/common-security/readme.MD

@ -4,10 +4,10 @@
    1. 获取客户端的实现逻辑结合自己的客户端用户体系实现 (com.yihu.base.security.rbas.ClientServiceProvider)
第一步
获取code
http://localhost:8060/oauth/authorize?response_type=code&client_id=cwd&redirect_uri=http://example.com&scope=all
http://localhost:8060/oauth/authorize?response_type=code&client_id=cwd&redirect_uri=http://example.com&scope=app
参数说明:
response_type=code 固定
scope=all 固定
scope=app 固定
client_id=cwd 根据用户表中自己定义的填写
redirect_uri=http://example.com 根据用户表中自己定义的填写
@ -21,7 +21,7 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
     "client_id":"cwd",
     "code":"第一步请求获取的code",
     "redirect_uri":"http://example.com",
     "scope":"all"
     "scope":"app"
}
返回值
{
@ -29,7 +29,7 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
    "token_type":"bearer",
    "refresh_token":"1427b997-ef94-4061-8940-c71da6549acd",  默认2小时过期时间 可以配置 
    "expires_in":43199,
    "scope":"all"
    "scope":"app"
}
**密码模式(一般自己公司系统用)**
@ -43,9 +43,9 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"password",  
     "username":"jojo",
     "username":"admin",
     "password":"123456",
     "scope":"all"
     "scope":"app"
}
返回值
@ -54,9 +54,10 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
    "scope":"app"
}
**刷新token**
获取token post请求
http://localhost:8060/oauth/token
@ -64,7 +65,7 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"refresh_token",
     "refresh_token":"all"
     "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3"
}
返回值
@ -73,7 +74,7 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
    "scope":"app"
}
@ -87,7 +88,7 @@ header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
注:  
    1. 获取用户的实现逻辑结合自己的用户体系实现 (org.springframework.security.core.userdetails.UserDetailsService)
body
{
{ 
    "username":"test",
    "password":"123456"
}
@ -99,7 +100,12 @@ body
    "expires_in":43199,
    "scope":"all"
}
{
    "access_token":"4ce54971-91f9-4c19-bf76-a3c1d3e8c495",
    "token_type":"bearer",
    "refresh_token":"37e3e3bc-8897-4eb4-b43b-4b8382f0efdf",
    "scope":"app"
}
**自定义手机号短信验证码登陆**
@ -137,7 +143,7 @@ body
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
    "scope":"app"
}
**访问方式**

+ 7 - 12
base/common-security/src/main/java/com.yihu.base.security/config/AuthorizationServerConfig.java

@ -5,26 +5,19 @@ import com.yihu.base.security.properties.AccessTokenPorperties;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.rbas.ClientServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
@ -46,8 +39,6 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private AccessTokenPorperties accessTokenPorperties;
@ -62,7 +53,11 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
        endpoints.authenticationManager(oAuth2AuthenticationManager())
                .tokenStore(tokenStore())
                .userDetailsService(userDetailsService)
                .tokenServices(defaultTokenServices());
                .tokenServices(defaultTokenServices())
               // .pathMapping("/oauth/confirm_access", "/extenal/oauth/confirm_access");//授权码模式  授权页面转换
        ;
        //endpoints.setClientDetailsService(clientDetailsService);
    }
@ -71,7 +66,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //.jdbc(dataSource).passwordEncoder(passwordEncoder) .clients(clientDetailsService)
        clients.withClientDetails(clientDetailsService) ;
        clients.withClientDetails(clientDetailsService);
        ;
    }
@ -99,6 +94,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setAccessTokenValiditySeconds(60 * 60 * accessTokenPorperties.getAccessTokenValidityHours()); //默认2小时
        defaultTokenServices.setRefreshTokenValiditySeconds(60 * 60 * accessTokenPorperties.getRefreshTokenValidityHours());//默认2小时
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        return defaultTokenServices;
    }
@ -107,7 +103,6 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
    TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(SecurityProperties.prefix_accesstoken);
        return redisTokenStore;
    }
}

+ 3 - 1
base/common-security/src/main/java/com.yihu.base.security/config/ResourceServerConfig.java

@ -4,13 +4,13 @@ import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.rbas.provider.AuthorizeConfigProviderManager;
import com.yihu.base.security.sms.SmsCodeAuthenticationSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
@ -21,6 +21,7 @@ import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.Base64Utils;
/**
 * Created by chenweida on 2017/12/4.
@ -84,4 +85,5 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
        expressionHandler.setApplicationContext(applicationContext);
        return expressionHandler;
    }
}

+ 19 - 2
base/common-security/src/main/java/com.yihu.base.security/hander/BaseAuthenticationSuccessHandler.java

@ -4,7 +4,9 @@
package com.yihu.base.security.hander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.rbas.ClientServiceProvider;
import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
@ -14,6 +16,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
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.*;
@ -21,6 +24,8 @@ import org.springframework.security.oauth2.provider.token.AuthorizationServerTok
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import javax.annotation.Resource;
import javax.servlet.ServletException;
@ -39,12 +44,20 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ClientServiceProvider clientDetailsService;
    @Autowired
    private AuthorizationServerTokenServices defaultTokenServices;
    @Autowired
    private SmsValidateCodeProcessor smsValidateCodeProcessor;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /*
         * (non-Javadoc)
@ -66,13 +79,13 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecurity = tokens[1];
        String clientSecurity =tokens[1];
        //得到ClientDetails
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        if (clientDetails == null) {
            throw new UnapprovedClientAuthenticationException("clientId不存在 client:" + clientId);
        } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecurity)) {
        } else if (!passwordEncoder.matches(clientSecurity,clientDetails.getClientSecret())) {
            throw new UnapprovedClientAuthenticationException("clientSecurity 不匹配 client:" + clientId);
        }
@ -84,6 +97,10 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
        OAuth2AccessToken token = defaultTokenServices.createAccessToken(oAuth2Authentication);
        if(pathMatcher.match(SecurityProperties.mobileLogin, request.getRequestURI())){
            //验证码模式登陆,说明登陆成功  删除验证码
            smsValidateCodeProcessor.reomve(new ServletWebRequest(request,response));
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(token));

+ 21 - 0
base/common-security/src/main/java/com.yihu.base.security/properties/QQProperties.java

@ -0,0 +1,21 @@
package com.yihu.base.security.properties;
import org.springframework.boot.autoconfigure.social.SocialProperties;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/12/9.
 */
@Component
public class QQProperties extends SocialProperties {
    private String providerId = "qq";
    public String getProviderId() {
        return providerId;
    }
    public void setProviderId(String providerId) {
        this.providerId = providerId;
    }
}

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationFilter.java

@ -15,7 +15,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author zhailiang
 * @author chenweida
 *
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationProvider.java

@ -11,7 +11,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
 * @author zhailiang
 * @author chenweida
 *
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

+ 32 - 28
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationSecurityConfig.java

@ -1,8 +1,9 @@
/**
 * 
 *
 */
package com.yihu.base.security.sms;
import com.yihu.base.security.sms.filter.SmsvalidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
@ -15,35 +16,38 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
import org.springframework.stereotype.Component;
/**
 * @author zhailiang
 *
 * @author chenweida
 */
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
	
	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;
	
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		
		SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
		smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
		smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
		
		SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
		smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
		
		http.authenticationProvider(smsCodeAuthenticationProvider)
			.addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
		
	}
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private SmsvalidateCodeFilter smsvalidateCodeFilter;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(smsvalidateCodeFilter,SmsCodeAuthenticationFilter.class);
        ;
    }
}

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationToken.java

@ -10,7 +10,7 @@ import org.springframework.security.core.SpringSecurityCoreVersion;
import java.util.Collection;
/**
 * @author zhailiang
 * @author chenweida
 *
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/sms/controller/SmsController.java

@ -44,7 +44,7 @@ public class SmsController {
            response.setHeader("content-type", "text/html;charset=UTF-8");
            response.setStatus(HttpStatus.NOT_IMPLEMENTED.value());//参数错误
            PrintWriter pw = response.getWriter();
            pw.write(new String("电话号码格式错误"));
            pw.write(new String("{\"content\":\"电话号码格式错误\"}"));
            pw.flush();
        } else {
            //发送短信验证码并且保存到redis中

+ 3 - 3
base/common-security/src/main/java/com.yihu.base.security/sms/filter/SmsvalidateCodeFilter.java

@ -24,7 +24,7 @@ import java.io.IOException;
/**
 * @author chenweida
 */
@Component("smsvalidateCodeFilter")
@Component
public class SmsvalidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    /**
@ -45,8 +45,8 @@ public class SmsvalidateCodeFilter extends OncePerRequestFilter implements Initi
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            if (pathMatcher.match(SecurityProperties.mobileSendSms, request.getRequestURI())) {
        if (StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
            if (pathMatcher.match(SecurityProperties.mobileLogin, request.getRequestURI())) {
                logger.info("校验请求(" + request.getRequestURI() + ")中的验证码");
                try {
                    smsValidateCodeProcessor.validate(new ServletWebRequest(request, response));

+ 2 - 2
base/common-security/src/main/java/com.yihu.base.security/sms/mobile/DefaultMobileCheck.java

@ -17,13 +17,13 @@ public class DefaultMobileCheck implements MobileCheck {
     * <p>
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189
     * 电信号码段:133、153、180、189,181
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,5-9]))\\d{8}$";
        return check(cellphone, regex);
    }

+ 8 - 10
base/common-security/src/main/java/com.yihu.base.security/sms/process/SmsValidateCodeProcessor.java

@ -53,7 +53,7 @@ public class SmsValidateCodeProcessor implements ValidateCodeProcessor {
     * @return
     */
    @SuppressWarnings("unchecked")
    private ValidateCode generate(ServletWebRequest request) {
    public ValidateCode generate(ServletWebRequest request) {
        return smsValidateCodeGenerator.generate(request);
    }
@ -63,7 +63,7 @@ public class SmsValidateCodeProcessor implements ValidateCodeProcessor {
     * @param request
     * @param validateCode
     */
    private void save(ServletWebRequest request, ValidateCode validateCode) {
    public void save(ServletWebRequest request, ValidateCode validateCode) {
        JSONObject jo = new JSONObject();
        jo.put("code", validateCode.getCode());//保存验证码
        jo.put("expireTime", validateCode.getExpireTimeString()); //保存超时时间
@ -76,7 +76,7 @@ public class SmsValidateCodeProcessor implements ValidateCodeProcessor {
     *
     * @param request
     */
    private void reomve(ServletWebRequest request) {
    public void reomve(ServletWebRequest request) {
        redisTemplate.delete((key(request)));
    }
@ -126,33 +126,31 @@ public class SmsValidateCodeProcessor implements ValidateCodeProcessor {
        //获取验证码
        ValidateCode validateCode = get(request);
        if (validateCode == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        String codeInRequest;
        //获取请求中的验证码
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    SecurityProperties.mobileSendSms);
                    SecurityProperties.mobileLoginSmsKey);
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }
        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if (validateCode == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        if (validateCode.isExpried()) {
            reomve(request);
            throw new ValidateCodeException("验证码已过期");
        }
        if (!StringUtils.equals(validateCode.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        //验证成功删除验证码
        reomve(request);
    }
}

+ 0 - 3
base/common-security/src/main/java/com.yihu.base.security/sms/sender/DefaultSmsCodeSender.java

@ -15,9 +15,6 @@ import org.springframework.stereotype.Component;
public class DefaultSmsCodeSender implements SmsCodeSender {
    private Logger logger = LoggerFactory.getLogger(DefaultSmsCodeSender.class);
    /* (non-Javadoc)
     * @see com.imooc.security.core.validate.code.sms.SmsCodeSender#send(java.lang.String, java.lang.String)
     */
    @Override
    public void send(String mobile, String code) throws ValidateCodeException {
        logger.info("向手机" + mobile + "发送短信验证码" + code);

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/sms/vo/ValidateCode.java

@ -26,7 +26,7 @@ public class ValidateCode implements Serializable {
    public ValidateCode(String code, int expireIn) {
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
        this.expireTime = LocalDateTime.now().plusMinutes(expireIn);
    }
    public ValidateCode(String code, LocalDateTime expireTime) {

+ 13 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQ.java

@ -0,0 +1,13 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.api;
/**
 *
 */
public interface QQ {
	
	QQUserInfo getUserInfo();
}

+ 60 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQImpl.java

@ -0,0 +1,60 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
/**
 *
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
	
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	
	private String appId;
	
	private String openId;
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	public QQImpl(String accessToken, String appId) {
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		
		this.appId = appId;
		
		String url = String.format(URL_GET_OPENID, accessToken);
		String result = getRestTemplate().getForObject(url, String.class);
		
		System.out.println(result);
		
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}
	
	/* (non-Javadoc)
	 * @see com.imooc.security.core.social.qq.api.QQ#getUserInfo()
	 */
	@Override
	public QQUserInfo getUserInfo() {
		
		String url = String.format(URL_GET_USERINFO, appId, openId);
		String result = getRestTemplate().getForObject(url, String.class);
		
		System.out.println(result);
		
		QQUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}
}

+ 206 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/api/QQUserInfo.java

@ -0,0 +1,206 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.api;
/**
 *
 */
public class QQUserInfo {
	
	/**
	 * 	返回码
	 */
	private String ret;
	/**
	 * 如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。
	 */
	private String msg;
	/**
	 * 
	 */
	private String openId;
	/**
	 * 不知道什么东西,文档上没写,但是实际api返回里有。
	 */
	private String is_lost;
	/**
	 * 省(直辖市)
	 */
	private String province;
	/**
	 * 市(直辖市区)
	 */
	private String city;
	/**
	 * 出生年月
	 */
	private String year;
	/**
	 * 	用户在QQ空间的昵称。
	 */
	private String nickname;
	/**
	 * 	大小为30×30像素的QQ空间头像URL。
	 */
	private String figureurl;
	/**
	 * 	大小为50×50像素的QQ空间头像URL。
	 */
	private String figureurl_1;
	/**
	 * 	大小为100×100像素的QQ空间头像URL。
	 */
	private String figureurl_2;
	/**
	 * 	大小为40×40像素的QQ头像URL。
	 */
	private String figureurl_qq_1;
	/**
	 * 	大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100×100的头像,但40×40像素则是一定会有。
	 */
	private String figureurl_qq_2;
	/**
	 * 	性别。 如果获取不到则默认返回”男”
	 */
	private String gender;
	/**
	 * 	标识用户是否为黄钻用户(0:不是;1:是)。
	 */
	private String is_yellow_vip;
	/**
	 * 	标识用户是否为黄钻用户(0:不是;1:是)
	 */
	private String vip;
	/**
	 * 	黄钻等级
	 */
	private String yellow_vip_level;
	/**
	 * 	黄钻等级
	 */
	private String level;
	/**
	 * 标识是否为年费黄钻用户(0:不是; 1:是)
	 */
	private String is_yellow_year_vip;
	
	
	public String getRet() {
		return ret;
	}
	public void setRet(String ret) {
		this.ret = ret;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getOpenId() {
		return openId;
	}
	public void setOpenId(String openId) {
		this.openId = openId;
	}
	public String getIs_lost() {
		return is_lost;
	}
	public void setIs_lost(String is_lost) {
		this.is_lost = is_lost;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getYear() {
		return year;
	}
	public void setYear(String year) {
		this.year = year;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getFigureurl() {
		return figureurl;
	}
	public void setFigureurl(String figureurl) {
		this.figureurl = figureurl;
	}
	public String getFigureurl_1() {
		return figureurl_1;
	}
	public void setFigureurl_1(String figureurl_1) {
		this.figureurl_1 = figureurl_1;
	}
	public String getFigureurl_2() {
		return figureurl_2;
	}
	public void setFigureurl_2(String figureurl_2) {
		this.figureurl_2 = figureurl_2;
	}
	public String getFigureurl_qq_1() {
		return figureurl_qq_1;
	}
	public void setFigureurl_qq_1(String figureurl_qq_1) {
		this.figureurl_qq_1 = figureurl_qq_1;
	}
	public String getFigureurl_qq_2() {
		return figureurl_qq_2;
	}
	public void setFigureurl_qq_2(String figureurl_qq_2) {
		this.figureurl_qq_2 = figureurl_qq_2;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getIs_yellow_vip() {
		return is_yellow_vip;
	}
	public void setIs_yellow_vip(String is_yellow_vip) {
		this.is_yellow_vip = is_yellow_vip;
	}
	public String getVip() {
		return vip;
	}
	public void setVip(String vip) {
		this.vip = vip;
	}
	public String getYellow_vip_level() {
		return yellow_vip_level;
	}
	public void setYellow_vip_level(String yellow_vip_level) {
		this.yellow_vip_level = yellow_vip_level;
	}
	public String getLevel() {
		return level;
	}
	public void setLevel(String level) {
		this.level = level;
	}
	public String getIs_yellow_year_vip() {
		return is_yellow_year_vip;
	}
	public void setIs_yellow_year_vip(String is_yellow_year_vip) {
		this.is_yellow_year_vip = is_yellow_year_vip;
	}
	
	
}

+ 36 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/config/QQAutoConfig.java

@ -0,0 +1,36 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.config;
import com.yihu.base.security.properties.QQProperties;
import com.yihu.base.security.social.qq.connet.QQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.social.SocialAutoConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.ConnectionFactory;
/**
 *
 */
@Configuration
@ConditionalOnProperty(prefix = "imooc.security.social.qq", name = "app-id")
public class QQAutoConfig extends SocialAutoConfigurerAdapter {
	@Autowired
	private QQProperties qqConfig;
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.boot.autoconfigure.social.SocialAutoConfigurerAdapter
	 * #createConnectionFactory()
	 */
	@Override
	protected ConnectionFactory<?> createConnectionFactory() {
		return new QQConnectionFactory(qqConfig.getProviderId(), qqConfig.getAppId(), qqConfig.getAppSecret());
	}
}

+ 43 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQAdapter.java

@ -0,0 +1,43 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.connet;
import com.yihu.base.security.social.qq.api.QQ;
import com.yihu.base.security.social.qq.api.QQUserInfo;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
/**
 *
 */
public class QQAdapter implements ApiAdapter<QQ> {
	@Override
	public boolean test(QQ api) {
		return true;
	}
	@Override
	public void setConnectionValues(QQ api, ConnectionValues values) {
		QQUserInfo userInfo = api.getUserInfo();
		
		values.setDisplayName(userInfo.getNickname());
		values.setImageUrl(userInfo.getFigureurl_qq_1());
		values.setProfileUrl(null);
		values.setProviderUserId(userInfo.getOpenId());
	}
	@Override
	public UserProfile fetchUserProfile(QQ api) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void updateStatus(QQ api, String message) {
		//do noting
	}
}

+ 18 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQConnectionFactory.java

@ -0,0 +1,18 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.connet;
import com.yihu.base.security.social.qq.api.QQ;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
/**
 *
 */
public class QQConnectionFactory extends OAuth2ConnectionFactory<QQ> {
	public QQConnectionFactory(String providerId, String appId, String appSecret) {
		super(providerId, new QQServiceProvider(appId, appSecret), new QQAdapter());
	}
}

+ 51 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQOAuth2Template.java

@ -0,0 +1,51 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.connet;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
/**
 *
 */
public class QQOAuth2Template extends OAuth2Template {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
		super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
		setUseParametersForClientAuthentication(true);
	}
	
	@Override
	protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
		String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
		
		logger.info("获取accessToke的响应:"+responseStr);
		
		String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
		
		String accessToken = StringUtils.substringAfterLast(items[0], "=");
		Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
		String refreshToken = StringUtils.substringAfterLast(items[2], "=");
		
		return new AccessGrant(accessToken, null, refreshToken, expiresIn);
	}
	
	@Override
	protected RestTemplate createRestTemplate() {
		RestTemplate restTemplate = super.createRestTemplate();
		restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
		return restTemplate;
	}
}

+ 32 - 0
base/common-security/src/main/java/com.yihu.base.security/social/qq/connet/QQServiceProvider.java

@ -0,0 +1,32 @@
/**
 * 
 */
package com.yihu.base.security.social.qq.connet;
import com.yihu.base.security.social.qq.api.QQ;
import com.yihu.base.security.social.qq.api.QQImpl;
import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider;
/**
 *
 */
public class QQServiceProvider extends AbstractOAuth2ServiceProvider<QQ> {
	private String appId;
	
	private static final String URL_AUTHORIZE = "https://graph.qq.com/oauth2.0/authorize";
	
	private static final String URL_ACCESS_TOKEN = "https://graph.qq.com/oauth2.0/token";
	
	public QQServiceProvider(String appId, String appSecret) {
		super(new QQOAuth2Template(appId, appSecret, URL_AUTHORIZE, URL_ACCESS_TOKEN));
		this.appId = appId;
	}
	
	@Override
	public QQ getApi(String accessToken) {
		return new QQImpl(accessToken, appId);
	}
}

+ 1 - 1
base/common-security/src/main/resources/template.yml

@ -23,7 +23,7 @@ spring:
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    database: 1
    database: 0
  aop:
    proxy-target-class: true

+ 26 - 3
svr-lib-parent-pom/pom.xml

@ -52,9 +52,12 @@
        <version.myCommon>1.0.0</version.myCommon>
        <version.spring>4.3.10.RELEASE</version.spring>
        <version.spring.security>4.2.3.RELEASE</version.spring.security>
        <version.spring-data-jpa>1.11.3.RELEASE</version.spring-data-jpa>
        <version.spring-data-common>1.13.3.RELEASE</version.spring-data-common>
        <version.spring-data-hadoop>2.3.0.RELEASE</version.spring-data-hadoop>
        <version.spring-data.solr>2.1.8.RELEASE</version.spring-data.solr>
        <version.spring.social>1.1.4.RELEASE</version.spring.social>
        <version.zipkin>1.24.0</version.zipkin>
        <version.hibernate>5.0.12.Final</version.hibernate>
        <version.hibernate-jpa>1.0.0.Final</version.hibernate-jpa>
@ -82,10 +85,8 @@
        <version.elasticsearch>2.4.4</version.elasticsearch>
        <version.jest>2.4.0</version.jest>
        <version.hbase-client>1.1.1</version.hbase-client>
        <version.spring-data-hadoop>2.3.0.RELEASE</version.spring-data-hadoop>
        <version.joda-time>2.8.2</version.joda-time>
        <version.solr>5.5.1</version.solr>
        <version.spring-data.solr>2.1.8.RELEASE</version.spring-data.solr>
        <version.fastdfs>1.25</version.fastdfs>
    </properties>
    <!--dependencyManagement作用子配置不写版本默认继承父配置-->
@ -425,6 +426,28 @@
            </dependency>
            <!--spring end-->
            <!--spring social start-->
            <dependency>
                <groupId>org.springframework.social</groupId>
                <artifactId>spring-social-config</artifactId>
                <version>${version.spring.social}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.social</groupId>
                <artifactId>spring-social-core</artifactId>
                <version>${version.spring.social}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.social</groupId>
                <artifactId>spring-social-security</artifactId>
                <version>${version.spring.social}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.social</groupId>
                <artifactId>spring-social-web</artifactId>
                <version>${version.spring.social}</version>
            </dependency>
            <!--spring  social end-->
            <!--数据库驱动 start-->
            <dependency>
                <groupId>mysql</groupId>

+ 7 - 1
svr/svr-demo/src/main/java/com/yihu/jw/model/SaasDO.java

@ -159,6 +159,7 @@ public class SaasDO implements Serializable, ClientDetails {
        strings.add("password");
        strings.add("custom_password");
        strings.add("authorization_code");
        strings.add("implicit");
        strings.add("refresh_token");
        return strings;
    }
@ -190,9 +191,14 @@ public class SaasDO implements Serializable, ClientDetails {
        return 0;
    }
    /**
     * 是否自动授权
     * @param scope
     * @return
     */
    @Override
    public boolean isAutoApprove(String scope) {
        return false;
        return true;
    }
    @Override

+ 9 - 1
svr/svr-demo/src/main/java/com/yihu/jw/service/ClientService.java

@ -2,6 +2,10 @@ package com.yihu.jw.service;
import com.yihu.base.security.rbas.ClientServiceProvider;
import com.yihu.jw.model.SaasDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;
@ -10,7 +14,10 @@ import org.springframework.stereotype.Component;
 * Created by chenweida on 2017/12/1.
 */
@Component("baseClientDetailsService")
@Primary
public class ClientService implements ClientServiceProvider {
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 根据自己的业务查询表 返回相关的平台用户信息
     * @param clientId
@ -27,9 +34,10 @@ public class ClientService implements ClientServiceProvider {
        SaasDO baseClientDetails = new SaasDO();
        baseClientDetails.setAppId("cwd");
        baseClientDetails.setAppSecret("cwd");
        baseClientDetails.setAppSecret( passwordEncoder.encode("cwd"));
        baseClientDetails.getAuthorizedGrantTypes();
        return baseClientDetails;
    }
}

+ 2 - 1
svr/svr-demo/src/main/java/com/yihu/jw/service/RbasService.java

@ -41,7 +41,8 @@ public class RbasService implements IRbasService {
                }
            }
        }
        return hasPerssion;
        return true;
        //return hasPerssion;
    }
}

+ 9 - 0
svr/svr-demo/src/main/java/com/yihu/jw/service/UserService.java

@ -3,6 +3,7 @@ package com.yihu.jw.service;
import com.yihu.jw.model.SaasDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@ -10,12 +11,14 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
@ -28,6 +31,7 @@ import java.util.Set;
 * 处理用户校验
 */
@Component
@Primary
public class UserService implements UserDetailsService {
    @Autowired
@ -67,4 +71,9 @@ public class UserService implements UserDetailsService {
        }
    }
    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        System.out.println(new String(Base64Utils.encode(("cwd:"+bCryptPasswordEncoder.encode("cwd")).getBytes())));
    }
}

+ 2 - 2
svr/svr-demo/src/main/resources/application.yml

@ -28,9 +28,9 @@ spring:
  redis:
    host: 172.19.103.88 # Redis server host.
    host: 127.0.0.1 # Redis server host.
    port: 6379 # Redis server port.
    database: 1
    database: 6
  aop:
    proxy-target-class: true