Ver código fonte

update:权限认证重构

yonge 6 anos atrás
pai
commit
eb1cb4953d
24 arquivos alterados com 592 adições e 230 exclusões
  1. 3 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/AuthorizationServerConfig.java
  2. 52 40
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/WebSecurityConfig.java
  3. 0 36
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/SmsCodeAuthenticationProvider.java
  4. 40 10
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/token/PhoneAuthenticationToken.java
  5. 70 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/PhoneLoginAuthenticationFilter.java
  6. 15 4
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/UsernameAuthenticationFilter.java
  7. 1 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/WebResponseExceptionTranslator.java
  8. 1 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/handler/BaseAuthenticationFailureEvenHandler.java
  9. 3 3
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/handler/BaseAuthenticationSuccessEventHandler.java
  10. 167 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/AbstractAuthenticationProvider.java
  11. 72 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/PhoneAuthenticationProvider.java
  12. 3 2
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/service/PhoneUserDetailService.java
  13. 2 2
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/service/UsernameUserDetailsService.java
  14. 41 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/service/AccessTokenService.java
  15. 0 45
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/SmsCodeAuthenticationFilter.java
  16. 0 28
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/SmsCodeService.java
  17. 0 49
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/impl/SmsCodeServiceImpl.java
  18. 6 4
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/SmsCodeController.java
  19. 33 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/TokenController.java
  20. 2 2
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/UserController.java
  21. 1 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/queryInfo/SysUserQueryInfo.java
  22. 2 0
      mec-common/src/main/java/com/ym/mec/common/redis/service/RedisCache.java
  23. 33 0
      mec-common/src/main/java/com/ym/mec/common/validcode/SmsCodeService.java
  24. 45 0
      mec-common/src/main/java/com/ym/mec/common/validcode/impl/SmsCodeServiceImpl.java

+ 3 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/AuthorizationServerConfig.java

@@ -1,7 +1,8 @@
 package com.ym.mec.auth.config;
 
-import com.ym.mec.auth.filter.WebResponseExceptionTranslator;
+import com.ym.mec.auth.core.filter.WebResponseExceptionTranslator;
 import com.ym.mec.common.constant.CommonConstants;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
@@ -15,6 +16,7 @@ import org.springframework.security.oauth2.config.annotation.web.configurers.Aut
 import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
 import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
 import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
+
 import javax.sql.DataSource;
 
 /**

+ 52 - 40
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/WebSecurityConfig.java

@@ -1,18 +1,9 @@
 package com.ym.mec.auth.config;
 
-import com.ym.mec.auth.config.provider.service.BaseUserDetailsService;
-import com.ym.mec.auth.config.provider.service.SmsCodeAuthenticationProvider;
-import com.ym.mec.auth.filter.BaseAuthenticationFilter;
-import com.ym.mec.auth.filter.SmsCodeAuthenticationFilter;
-import com.ym.mec.auth.handler.BaseAuthenticationFailureEvenHandler;
-import com.ym.mec.auth.handler.BaseAuthenticationSuccessEventHandler;
-import com.ym.mec.common.security.BaseAccessDeniedHandler;
-import com.ym.mec.common.security.BaseAuthenticationEntryPoint;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.ProviderManager;
 import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@@ -22,8 +13,16 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 import org.springframework.security.crypto.factory.PasswordEncoderFactories;
 import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
-import java.util.Arrays;
+import com.ym.mec.auth.core.filter.PhoneLoginAuthenticationFilter;
+import com.ym.mec.auth.core.filter.UsernameAuthenticationFilter;
+import com.ym.mec.auth.core.handler.BaseAuthenticationFailureEvenHandler;
+import com.ym.mec.auth.core.handler.BaseAuthenticationSuccessEventHandler;
+import com.ym.mec.auth.core.provider.PhoneAuthenticationProvider;
+import com.ym.mec.auth.core.provider.service.PhoneUserDetailService;
+import com.ym.mec.auth.core.provider.service.UsernameUserDetailsService;
+import com.ym.mec.common.validcode.SmsCodeService;
 
 @Configuration
 @EnableWebSecurity
@@ -31,57 +30,57 @@ import java.util.Arrays;
 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
 	@Autowired
-	private BaseUserDetailsService baseUserDetailsService;
+	private UsernameUserDetailsService usernameUserDetailsService;
+	
 	@Autowired
-	private SmsCodeAuthenticationProvider smsCodeAuthenticationProvider;
+	private PhoneUserDetailService phoneUserDetailService;
+	
+	@Autowired
+	private PhoneAuthenticationProvider phoneAuthenticationProvider;
+	
 	@Autowired
 	private BaseAuthenticationSuccessEventHandler successEventHandler;
+	
 	@Autowired
 	private BaseAuthenticationFailureEvenHandler failureEvenHandler;
+	
 	@Autowired
-	private BaseAccessDeniedHandler baseAccessDeniedHandler;
-	@Autowired
-	private BaseAuthenticationEntryPoint baseAuthenticationEntryPoint;
-
+	private SmsCodeService smsCodeService;
+	
 	@Override
 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 		auth.authenticationProvider(daoAuthenticationProvider());
+		
+		PhoneAuthenticationProvider provider = phoneAuthenticationProvider();
+		provider.setSmsCodeService(smsCodeService);
+		auth.authenticationProvider(provider);
 	}
 
 	@Override
 	protected void configure(HttpSecurity http) throws Exception {
 		// 表单登录 方式
 		http
-				.formLogin()
-				.loginPage("/loginIn")
-				.loginPage("/smsLogin")
-				.successHandler(successEventHandler)
-				.failureHandler(failureEvenHandler)
-			.and()
-				.exceptionHandling()
-				.accessDeniedHandler(baseAccessDeniedHandler)
-				.authenticationEntryPoint(baseAuthenticationEntryPoint)// 当未登录访问资源时
-			.and()// 请求授权
+			.addFilterBefore(getUsernameAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
+			.addFilterBefore(getPhoneLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
+			.formLogin().loginPage("/loginIn").loginPage("/smsLogin").and()
+				//.exceptionHandling().accessDeniedHandler(baseAccessDeniedHandler).authenticationEntryPoint(baseAuthenticationEntryPoint).and()// 当未登录访问资源时
+				// 请求授权
 				.authorizeRequests()// 不需要权限认证的url
-				.antMatchers("/oauth/**").permitAll()// 任何请求
+				.antMatchers("/usernameLogin","/smsLogin", "/refreshToken", "/v2/api-docs").permitAll()// 任何请求
 				.anyRequest()// 需要身份认证
-				.authenticated()
-			.and()// 关闭跨站请求防护
-				.csrf()
-				.disable();
+				.authenticated().and()// 关闭跨站请求防护
+				.csrf().disable();
 	}
 
 	@Override
 	public void configure(WebSecurity web) throws Exception {
-		web.ignoring().antMatchers("/loginIn","/smsLogin", "/refreshToken","/v2/api-docs");
+		web.ignoring().antMatchers("/usernameLogin", "/smsLogin", "/refreshToken", "/v2/api-docs");
 	}
 
 	@Bean
 	@Override
 	public AuthenticationManager authenticationManagerBean() throws Exception {
-		ProviderManager authenticationManager = new ProviderManager(Arrays.asList(smsCodeAuthenticationProvider,daoAuthenticationProvider()));
-		authenticationManager.setEraseCredentialsAfterAuthentication(false);
-		return authenticationManager;
+		return super.authenticationManagerBean();
 	}
 
 	@Bean
@@ -93,7 +92,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 	public DaoAuthenticationProvider daoAuthenticationProvider() {
 		DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
 		// 设置userDetailsService
-		provider.setUserDetailsService(baseUserDetailsService);
+		provider.setUserDetailsService(usernameUserDetailsService);
 		// 禁止隐藏用户未找到异常
 		provider.setHideUserNotFoundExceptions(false);
 		// 使用BCrypt进行密码的hash
@@ -101,17 +100,30 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 		return provider;
 	}
 
+    @Bean
+    public PhoneAuthenticationProvider phoneAuthenticationProvider(){
+    	PhoneAuthenticationProvider provider = new PhoneAuthenticationProvider();
+        // 设置userDetailsService
+        provider.setUserDetailsService(phoneUserDetailService);
+        //provider.setSmsCodeService(smsCodeService);
+		// 禁止隐藏用户未找到异常
+		provider.setHideUserNotFoundExceptions(false);
+		
+        return provider;
+    }
+
 	@Bean
-	public BaseAuthenticationFilter getBaseAuthenticationFilter() throws Exception {
-		BaseAuthenticationFilter filter = new BaseAuthenticationFilter();
+	public UsernameAuthenticationFilter getUsernameAuthenticationFilter() throws Exception {
+		UsernameAuthenticationFilter filter = new UsernameAuthenticationFilter();
 		filter.setAuthenticationManager(authenticationManagerBean());
 		filter.setAuthenticationSuccessHandler(successEventHandler);
 		filter.setAuthenticationFailureHandler(failureEvenHandler);
 		return filter;
 	}
+
 	@Bean
-	public SmsCodeAuthenticationFilter getSmsCodeAuthenticationFilter() throws Exception {
-		SmsCodeAuthenticationFilter filter = new SmsCodeAuthenticationFilter();
+	public PhoneLoginAuthenticationFilter getPhoneLoginAuthenticationFilter() throws Exception {
+		PhoneLoginAuthenticationFilter filter = new PhoneLoginAuthenticationFilter();
 		filter.setAuthenticationManager(authenticationManagerBean());
 		filter.setAuthenticationSuccessHandler(successEventHandler);
 		filter.setAuthenticationFailureHandler(failureEvenHandler);

+ 0 - 36
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/SmsCodeAuthenticationProvider.java

@@ -1,36 +0,0 @@
-package com.ym.mec.auth.config.provider.service;
-
-import com.ym.mec.auth.config.token.PhoneAuthenticationToken;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.stereotype.Component;
-
-@Component
-public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
-
-    @Autowired
-    private SmsUserDetailService userDetailService;
-
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        PhoneAuthenticationToken authenticationToken = (PhoneAuthenticationToken) authentication;
-
-        UserDetails user = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());
-        if (user == null) {
-            return null;
-        }
-
-        PhoneAuthenticationToken authenticationResult = new PhoneAuthenticationToken(user,user.getAuthorities());
-        authenticationResult.setDetails(authenticationToken.getDetails());
-
-        return authenticationResult;
-    }
-
-    @Override
-    public boolean supports(Class<?> aClass) {
-        return PhoneAuthenticationToken.class.isAssignableFrom(aClass);
-    }
-}

+ 40 - 10
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/token/PhoneAuthenticationToken.java

@@ -4,34 +4,63 @@ import java.util.Collection;
 
 import org.springframework.security.authentication.AbstractAuthenticationToken;
 import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.SpringSecurityCoreVersion;
 
 /**
  * 手机验证码token
  */
 public class PhoneAuthenticationToken extends AbstractAuthenticationToken {
 
-	private static final long serialVersionUID = 110L;
+	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
+
+	// ~ Instance fields
+	// ================================================================================================
+
 	private final Object principal;
+	private Object credentials;
+
+	// ~ Constructors
+	// ===================================================================================================
 
-	public PhoneAuthenticationToken(Object mobile) {
+	/**
+	 * 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 PhoneAuthenticationToken(Object principal, Object credentials) {
 		super(null);
-		this.principal = mobile;
+		this.principal = principal;
+		this.credentials = credentials;
 		setAuthenticated(false);
 	}
 
-	public PhoneAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
+	/**
+	 * 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 credentials
+	 * @param authorities
+	 */
+	public PhoneAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
 		super(authorities);
 		this.principal = principal;
-		super.setAuthenticated(true);
+		this.credentials = credentials;
+		super.setAuthenticated(true); // must use super, as we override
 	}
 
-	public Object getPrincipal() {
-		return this.principal;
-	}
+	// ~ Methods
+	// ========================================================================================================
 
-	@Override
 	public Object getCredentials() {
-		return null;
+		return this.credentials;
+	}
+
+	public Object getPrincipal() {
+		return this.principal;
 	}
 
 	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
@@ -45,5 +74,6 @@ public class PhoneAuthenticationToken extends AbstractAuthenticationToken {
 	@Override
 	public void eraseCredentials() {
 		super.eraseCredentials();
+		credentials = null;
 	}
 }

+ 70 - 0
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/PhoneLoginAuthenticationFilter.java

@@ -0,0 +1,70 @@
+package com.ym.mec.auth.core.filter;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.authentication.AuthenticationServiceException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+
+import com.ym.mec.auth.config.token.PhoneAuthenticationToken;
+
+public class PhoneLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+
+    private static final String SPRING_SECURITY_RESTFUL_PHONE_KEY = "phone";
+    private static final String SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY = "smsCode";
+
+    private static final String SPRING_SECURITY_RESTFUL_LOGIN_URL = "/smsLogin";
+    private boolean postOnly = true;
+
+    public PhoneLoginAuthenticationFilter() {
+        super(new AntPathRequestMatcher(SPRING_SECURITY_RESTFUL_LOGIN_URL, "POST"));
+    }
+    
+    @Override
+    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
+        if (postOnly && !request.getMethod().equals("POST")) {
+            throw new AuthenticationServiceException(
+                    "Authentication method not supported: " + request.getMethod());
+        }
+
+        AbstractAuthenticationToken authRequest;
+        String principal;
+        String credentials;
+
+        // 手机验证码登陆
+        principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY);
+        credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY);
+
+        principal = principal.trim();
+        authRequest = new PhoneAuthenticationToken(principal, credentials);
+
+        // Allow subclasses to set the "details" property
+        setDetails(request, authRequest);
+        return this.getAuthenticationManager().authenticate(authRequest);
+    }
+
+	@Override
+	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
+			FilterChain chain, Authentication authResult) throws IOException, ServletException {
+		super.successfulAuthentication(request, response, chain, authResult);
+		chain.doFilter(request, response);
+	}
+
+    private void setDetails(HttpServletRequest request,
+                            AbstractAuthenticationToken authRequest) {
+        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
+    }
+
+    private String obtainParameter(HttpServletRequest request, String parameter) {
+        String result =  request.getParameter(parameter);
+        return result == null ? "" : result;
+    }
+}

+ 15 - 4
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/BaseAuthenticationFilter.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/UsernameAuthenticationFilter.java

@@ -1,4 +1,6 @@
-package com.ym.mec.auth.filter;
+package com.ym.mec.auth.core.filter;
+
+import java.io.IOException;
 
 import org.springframework.security.authentication.AuthenticationServiceException;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -8,10 +10,12 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro
 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 import org.springframework.util.Assert;
 
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-public class BaseAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+public class UsernameAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
 
 	// ~ Static fields/initializers
 	// =====================================================================================
@@ -23,8 +27,8 @@ public class BaseAuthenticationFilter extends AbstractAuthenticationProcessingFi
 	// ~ Constructors
 	// ===================================================================================================
 
-	public BaseAuthenticationFilter() {
-		super(new AntPathRequestMatcher("/loginIn", "POST"));
+	public UsernameAuthenticationFilter() {
+		super(new AntPathRequestMatcher("/usernameLogin", "POST"));
 	}
 
 	// ~ Methods
@@ -61,6 +65,13 @@ public class BaseAuthenticationFilter extends AbstractAuthenticationProcessingFi
 		return this.getAuthenticationManager().authenticate(authRequest);
 	}
 
+	@Override
+	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
+			FilterChain chain, Authentication authResult) throws IOException, ServletException {
+		super.successfulAuthentication(request, response, chain, authResult);
+		chain.doFilter(request, response);
+	}
+
 	/**
 	 * Enables subclasses to override the composition of the password, such as by
 	 * including additional values and a separator.

+ 1 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/WebResponseExceptionTranslator.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/filter/WebResponseExceptionTranslator.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.filter;
+package com.ym.mec.auth.core.filter;
 
 import org.springframework.http.ResponseEntity;
 import org.springframework.security.authentication.InternalAuthenticationServiceException;

+ 1 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/handler/BaseAuthenticationFailureEvenHandler.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/handler/BaseAuthenticationFailureEvenHandler.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.handler;
+package com.ym.mec.auth.core.handler;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.ym.mec.common.entity.HttpResponseResult;

+ 3 - 3
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/handler/BaseAuthenticationSuccessEventHandler.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/handler/BaseAuthenticationSuccessEventHandler.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.handler;
+package com.ym.mec.auth.core.handler;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.ym.mec.common.entity.HttpResponseResult;
@@ -43,7 +43,7 @@ public class BaseAuthenticationSuccessEventHandler extends SavedRequestAwareAuth
 	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException,
 			IOException {
 		logger.info("用户:{} 登录成功", authentication.getPrincipal());
-		try {
+		/*try {
 			String clientId = request.getParameter("clientId");
 			String clientSecret = request.getParameter("clientSecret");
 			if (clientId == null || clientSecret == null) {
@@ -68,7 +68,7 @@ public class BaseAuthenticationSuccessEventHandler extends SavedRequestAwareAuth
 			response.getWriter().write(objectMapper.writeValueAsString(result));
 		} catch (IOException e) {
 			throw new BadCredentialsException("Failed to decode basic authentication token");
-		}
+		}*/
 	}
 
 	/**

+ 167 - 0
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/AbstractAuthenticationProvider.java

@@ -0,0 +1,167 @@
+package com.ym.mec.auth.core.provider;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.context.MessageSource;
+import org.springframework.context.MessageSourceAware;
+import org.springframework.context.support.MessageSourceAccessor;
+import org.springframework.security.authentication.AccountExpiredException;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.CredentialsExpiredException;
+import org.springframework.security.authentication.DisabledException;
+import org.springframework.security.authentication.LockedException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.SpringSecurityMessageSource;
+import org.springframework.security.core.userdetails.UserCache;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsChecker;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.core.userdetails.cache.NullUserCache;
+import org.springframework.util.Assert;
+
+public abstract class AbstractAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
+
+	protected final Log logger = LogFactory.getLog(this.getClass());
+	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
+	private UserCache userCache = new NullUserCache();
+	private boolean forcePrincipalAsString = false;
+	protected boolean hideUserNotFoundExceptions = true;
+	private UserDetailsChecker preAuthenticationChecks = new AbstractAuthenticationProvider.DefaultPreAuthenticationChecks();
+	private UserDetailsChecker postAuthenticationChecks = new AbstractAuthenticationProvider.DefaultPostAuthenticationChecks();
+
+	protected abstract void additionalAuthenticationChecks(UserDetails var1, Authentication var2) throws AuthenticationException;
+
+	public final void afterPropertiesSet() throws Exception {
+		Assert.notNull(this.userCache, "A user cache must be set");
+		Assert.notNull(this.messages, "A message source must be set");
+		this.doAfterPropertiesSet();
+	}
+
+	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+		String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
+		boolean cacheWasUsed = true;
+		UserDetails user = this.userCache.getUserFromCache(username);
+		if (user == null) {
+			cacheWasUsed = false;
+
+			try {
+				user = this.retrieveUser(username, authentication);
+			} catch (UsernameNotFoundException var6) {
+				this.logger.debug("User \'" + username + "\' not found");
+				if (this.hideUserNotFoundExceptions) {
+					throw new BadCredentialsException(this.messages.getMessage("MyAbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
+				}
+
+				throw var6;
+			}
+
+			Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
+		}
+
+		try {
+			this.preAuthenticationChecks.check(user);
+			this.additionalAuthenticationChecks(user, authentication);
+		} catch (AuthenticationException var7) {
+			if (!cacheWasUsed) {
+				throw var7;
+			}
+
+			cacheWasUsed = false;
+			user = this.retrieveUser(username, authentication);
+			this.preAuthenticationChecks.check(user);
+			this.additionalAuthenticationChecks(user, authentication);
+		}
+
+		this.postAuthenticationChecks.check(user);
+		if (!cacheWasUsed) {
+			this.userCache.putUserInCache(user);
+		}
+
+		Object principalToReturn = user;
+		if (this.forcePrincipalAsString) {
+			principalToReturn = user.getUsername();
+		}
+
+		return this.createSuccessAuthentication(principalToReturn, authentication, user);
+	}
+
+	protected abstract Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user);
+
+	protected void doAfterPropertiesSet() throws Exception {
+	}
+
+	public UserCache getUserCache() {
+		return this.userCache;
+	}
+
+	public boolean isForcePrincipalAsString() {
+		return this.forcePrincipalAsString;
+	}
+
+	public boolean isHideUserNotFoundExceptions() {
+		return this.hideUserNotFoundExceptions;
+	}
+
+	protected abstract UserDetails retrieveUser(String var1, Authentication var2) throws AuthenticationException;
+
+	public void setForcePrincipalAsString(boolean forcePrincipalAsString) {
+		this.forcePrincipalAsString = forcePrincipalAsString;
+	}
+
+	public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) {
+		this.hideUserNotFoundExceptions = hideUserNotFoundExceptions;
+	}
+
+	public void setMessageSource(MessageSource messageSource) {
+		this.messages = new MessageSourceAccessor(messageSource);
+	}
+
+	public void setUserCache(UserCache userCache) {
+		this.userCache = userCache;
+	}
+
+	protected UserDetailsChecker getPreAuthenticationChecks() {
+		return this.preAuthenticationChecks;
+	}
+
+	public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) {
+		this.preAuthenticationChecks = preAuthenticationChecks;
+	}
+
+	protected UserDetailsChecker getPostAuthenticationChecks() {
+		return this.postAuthenticationChecks;
+	}
+
+	public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
+		this.postAuthenticationChecks = postAuthenticationChecks;
+	}
+
+	private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
+		private DefaultPostAuthenticationChecks() {
+		}
+
+		public void check(UserDetails user) {
+			if (!user.isCredentialsNonExpired()) {
+				throw new CredentialsExpiredException("User account credentials have expired");
+			}
+		}
+	}
+
+	private class DefaultPreAuthenticationChecks implements UserDetailsChecker {
+		private DefaultPreAuthenticationChecks() {
+		}
+
+		public void check(UserDetails user) {
+			if (!user.isAccountNonLocked()) {
+				throw new LockedException("User account is locked");
+			} else if (!user.isEnabled()) {
+				throw new DisabledException("User account is disabled");
+			} else if (!user.isAccountNonExpired()) {
+				throw new AccountExpiredException("User account is expired");
+			}
+		}
+	}
+}

+ 72 - 0
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/PhoneAuthenticationProvider.java

@@ -0,0 +1,72 @@
+package com.ym.mec.auth.core.provider;
+
+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.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+
+import com.ym.mec.auth.config.token.PhoneAuthenticationToken;
+import com.ym.mec.common.validcode.SmsCodeService;
+
+public class PhoneAuthenticationProvider extends AbstractAuthenticationProvider {
+
+	private UserDetailsService userDetailsService;
+
+	private SmsCodeService smsCodeService;
+
+	@Override
+	protected void additionalAuthenticationChecks(UserDetails userDetails, Authentication authentication) throws AuthenticationException {
+		if (authentication.getCredentials() == null) {
+			throw new BadCredentialsException(this.messages.getMessage("PhoneAuthenticationProvider.badCredentials", "Bad credentials"));
+		} else {
+			String smsCode = authentication.getCredentials().toString();
+
+			String phone = authentication.getPrincipal().toString();
+
+			// 验证码验证
+			smsCodeService.verifyValidCode(phone, smsCode);
+		}
+	}
+
+	@Override
+	protected UserDetails retrieveUser(String phone, Authentication authentication) throws AuthenticationException {
+		UserDetails loadedUser;
+		try {
+			loadedUser = userDetailsService.loadUserByUsername(phone);
+		} catch (UsernameNotFoundException e) {
+			throw e;
+		} catch (Exception e) {
+			throw new InternalAuthenticationServiceException(e.getMessage(), e);
+		}
+
+		if (loadedUser == null) {
+			throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
+		} else {
+			return loadedUser;
+		}
+	}
+
+	@Override
+	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
+		PhoneAuthenticationToken result = new PhoneAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
+		result.setDetails(authentication.getDetails());
+		return result;
+	}
+
+	@Override
+	public boolean supports(Class<?> aClass) {
+		return PhoneAuthenticationToken.class.isAssignableFrom(aClass);
+	}
+
+	public void setUserDetailsService(UserDetailsService userDetailsService) {
+		this.userDetailsService = userDetailsService;
+	}
+
+	public void setSmsCodeService(SmsCodeService smsCodeService) {
+		this.smsCodeService = smsCodeService;
+	}
+
+}

+ 3 - 2
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/SmsUserDetailService.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/service/PhoneUserDetailService.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.config.provider.service;
+package com.ym.mec.auth.core.provider.service;
 
 import com.ym.mec.auth.api.dto.SysUserInfo;
 import com.ym.mec.auth.api.entity.SysUser;
@@ -15,7 +15,7 @@ import org.springframework.stereotype.Service;
 import java.util.List;
 
 @Service
-public class SmsUserDetailService implements UserDetailsService {
+public class PhoneUserDetailService implements UserDetailsService {
 
     @Autowired
     private SysUserService sysUserService;
@@ -33,4 +33,5 @@ public class SmsUserDetailService implements UserDetailsService {
         return new User(phone, "", StringUtils.equals(sysUser.getLockFlag(), "0"), true, true, true,
                 authorities);
     }
+
 }

+ 2 - 2
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/BaseUserDetailsService.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/provider/service/UsernameUserDetailsService.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.config.provider.service;
+package com.ym.mec.auth.core.provider.service;
 
 import com.ym.mec.auth.api.dto.SysUserInfo;
 import com.ym.mec.auth.api.entity.SysUser;
@@ -17,7 +17,7 @@ import org.springframework.stereotype.Service;
 import java.util.List;
 
 @Service
-public class BaseUserDetailsService implements UserDetailsService {
+public class UsernameUserDetailsService implements UserDetailsService {
 
 	@Autowired
 	private PasswordEncoder passwordEncoder;

+ 41 - 0
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/core/service/AccessTokenService.java

@@ -0,0 +1,41 @@
+package com.ym.mec.auth.core.service;
+
+import java.util.HashMap;
+
+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.exceptions.UnapprovedClientAuthenticationException;
+import org.springframework.security.oauth2.provider.ClientDetails;
+import org.springframework.security.oauth2.provider.ClientDetailsService;
+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.stereotype.Service;
+
+@Service
+public class AccessTokenService {
+
+	@Autowired
+	private ClientDetailsService clientDetailsService;
+
+	@Autowired
+	private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;
+
+	public OAuth2AccessToken getAccessToken(String clientId, String clientSecret, Authentication authentication) {
+
+		if (clientId == null || clientSecret == null) {
+			throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
+		}
+
+		ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
+		TokenRequest tokenRequest = new TokenRequest(new HashMap<String, String>(), clientId, clientDetails.getScope(), "password");
+		OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
+
+		OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
+		OAuth2AccessToken oAuth2AccessToken = defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication);
+
+		return oAuth2AccessToken;
+	}
+}

+ 0 - 45
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/SmsCodeAuthenticationFilter.java

@@ -1,45 +0,0 @@
-package com.ym.mec.auth.filter;
-
-import com.ym.mec.auth.config.token.PhoneAuthenticationToken;
-import com.ym.mec.auth.service.SmsCodeService;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.AuthenticationServiceException;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
-
-    private boolean postOnly = true;
-    @Autowired
-    private SmsCodeService smsCodeService;
-
-    public SmsCodeAuthenticationFilter(){
-        super(new AntPathRequestMatcher("/smsLogin", "POST"));
-    }
-    @Override
-    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
-        if (postOnly && !request.getMethod().equals("POST")) {
-            throw new AuthenticationServiceException(
-                    "Authentication method not supported: " + request.getMethod());
-        }
-        String code=request.getParameter("code");
-        String phone=request.getParameter("mobile");
-        if(!StringUtils.equals(code,(String)smsCodeService.getVerifyCode(phone))){
-            throw new BadCredentialsException(
-                    "验证码错误: " + code);
-        }
-        if (phone == null) {
-            phone = "";
-        }
-        phone = phone.trim();
-
-        PhoneAuthenticationToken authRequest = new PhoneAuthenticationToken(phone);
-        return this.getAuthenticationManager().authenticate(authRequest);
-    }
-}

+ 0 - 28
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/SmsCodeService.java

@@ -1,28 +0,0 @@
-package com.ym.mec.auth.service;
-
-import java.util.concurrent.TimeUnit;
-
-public interface SmsCodeService{
-
-    /**
-     * 发送登录验证码
-     * @return
-     */
-    boolean sendLoginVerifyCode(String mobile);
-
-    /**
-     * 获取验证码
-     *
-     * @param mobile 手机号
-     * @return 验证码
-     */
-    Object getVerifyCode(String mobile);
-
-
-    /**
-     * 删除验证码
-     *
-     * @param mobile
-     */
-    void removeVerifyCode(String mobile);
-}

+ 0 - 49
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/impl/SmsCodeServiceImpl.java

@@ -1,49 +0,0 @@
-package com.ym.mec.auth.service.impl;
-
-import com.ym.mec.auth.service.SmsCodeService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.core.ValueOperations;
-import org.springframework.stereotype.Service;
-import java.util.Random;
-
-@Service
-public class SmsCodeServiceImpl implements SmsCodeService {
-
-    @Autowired
-    private RedisTemplate<String,String> redisTemplate;
-    private final String loginVerifyCodeKey = "loginVerifyCode:";
-    private int expireTime = 60;
-
-    @Override
-    public boolean sendLoginVerifyCode(String mobile) {
-        String code = builderCode();
-        //发送验证码
-        System.out.println(code);
-        redisTemplate.opsForValue().set(loginVerifyCodeKey + mobile,code,expireTime);
-        return true;
-    }
-
-    @Override
-    public String getVerifyCode(String mobile) {
-        ValueOperations<String, String> operations = redisTemplate.opsForValue();
-        return operations.get(loginVerifyCodeKey + mobile);
-    }
-
-    @Override
-    public void removeVerifyCode(String mobile) {
-        if(redisTemplate.hasKey(loginVerifyCodeKey + mobile)){
-            redisTemplate.delete(loginVerifyCodeKey + mobile);
-        }
-    }
-
-    private String builderCode(){
-        String code = "";
-        Random random = new Random();
-        for (int i = 0; i < 6; i++) {
-            int r = random.nextInt(10);
-            code = code + r;
-        }
-        return code;
-    }
-}

+ 6 - 4
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/SmsCodeController.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/SmsCodeController.java

@@ -1,15 +1,17 @@
-package com.ym.mec.auth.controller;
+package com.ym.mec.auth.web.controller;
 
-import com.ym.mec.auth.service.SmsCodeService;
-import com.ym.mec.common.controller.BaseController;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiOperation;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
+import com.ym.mec.common.controller.BaseController;
+import com.ym.mec.common.validcode.SmsCodeService;
+
 @RestController
 @RequestMapping("sms")
 @Api(description = "短信服务")
@@ -22,7 +24,7 @@ public class SmsCodeController extends BaseController {
     @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String")
     @PostMapping("/sendVerifyCode")
     public Object sendLoginVerifyCode(String mobile) {
-        smsCodeService.sendLoginVerifyCode(mobile);
+        smsCodeService.sendValidCode(mobile);
         return succeed();
     }
 }

+ 33 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/TokenController.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/TokenController.java

@@ -1,9 +1,12 @@
-package com.ym.mec.auth.controller;
+package com.ym.mec.auth.web.controller;
 
 import java.io.IOException;
 import java.util.Base64;
 import java.util.Map;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpEntity;
@@ -11,6 +14,7 @@ import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.Authentication;
 import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
 import org.springframework.util.LinkedMultiValueMap;
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.client.RestTemplate;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ym.mec.auth.core.service.AccessTokenService;
 import com.ym.mec.common.controller.BaseController;
 import com.ym.mec.common.entity.HttpResponseResult;
 
@@ -35,6 +40,33 @@ public class TokenController extends BaseController {
 
 	@Autowired
 	private ObjectMapper objectMapper;
+	
+	@Autowired
+	private AccessTokenService accessTokenService;
+    
+    @PostMapping("/smsLogin")
+    public Object smsLogin(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
+    	
+    	String clientId = request.getParameter("clientId");
+		String clientSecret = request.getParameter("clientSecret");
+		if (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) {
+			return failed("没有指定客户端或秘钥");
+		}
+		
+        return succeed(accessTokenService.getAccessToken(clientId, clientSecret, authentication));
+    }
+    
+    @PostMapping("/usernameLogin")
+    public Object usernameLogin(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
+    	
+    	String clientId = request.getParameter("clientId");
+		String clientSecret = request.getParameter("clientSecret");
+		if (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) {
+			return failed("没有指定客户端或秘钥");
+		}
+		
+        return succeed(accessTokenService.getAccessToken(clientId, clientSecret, authentication));
+    }
 
 	@PostMapping(value = "/loginIn")
 	// @PreAuthorize("hasAnyAuthority('sys_user_manage')")

+ 2 - 2
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/UserController.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/UserController.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.controller;
+package com.ym.mec.auth.web.controller;
 
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
@@ -19,8 +19,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import com.ym.mec.auth.api.entity.SysUser;
-import com.ym.mec.auth.controller.queryInfo.SysUserQueryInfo;
 import com.ym.mec.auth.service.SysUserService;
+import com.ym.mec.auth.web.controller.queryInfo.SysUserQueryInfo;
 import com.ym.mec.common.controller.BaseController;
 
 @RestController()

+ 1 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/queryInfo/SysUserQueryInfo.java → mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/web/controller/queryInfo/SysUserQueryInfo.java

@@ -1,4 +1,4 @@
-package com.ym.mec.auth.controller.queryInfo;
+package com.ym.mec.auth.web.controller.queryInfo;
 
 import com.ym.mec.common.page.QueryInfo;
 

+ 2 - 0
mec-common/src/main/java/com/ym/mec/common/redis/service/RedisCache.java

@@ -5,10 +5,12 @@ import java.util.concurrent.TimeUnit;
 
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Component;
 
 import com.ym.mec.common.cache.Cache;
 import com.ym.mec.common.cache.CacheException;
 
+@Component
 public class RedisCache implements Cache {
 
 	private RedisTemplate<String, Object> redisTemplate;

+ 33 - 0
mec-common/src/main/java/com/ym/mec/common/validcode/SmsCodeService.java

@@ -0,0 +1,33 @@
+package com.ym.mec.common.validcode;
+
+public interface SmsCodeService {
+
+	/**
+	 * 校验验证码
+	 * @param mobile
+	 * @param authCode
+	 * @return
+	 */
+	boolean verifyValidCode(String mobile, String authCode);
+
+	/**
+	 * 发送登录验证码
+	 * @return
+	 */
+	boolean sendValidCode(String mobile);
+
+	/**
+	 * 获取验证码
+	 *
+	 * @param mobile 手机号
+	 * @return 验证码
+	 */
+	Object getValidCode(String mobile);
+
+	/**
+	 * 删除验证码
+	 *
+	 * @param mobile
+	 */
+	void removeValidCode(String mobile);
+}

+ 45 - 0
mec-common/src/main/java/com/ym/mec/common/validcode/impl/SmsCodeServiceImpl.java

@@ -0,0 +1,45 @@
+package com.ym.mec.common.validcode.impl;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.ym.mec.common.redis.service.RedisCache;
+import com.ym.mec.common.validcode.SmsCodeService;
+
+@Service
+public class SmsCodeServiceImpl implements SmsCodeService {
+
+	@Autowired
+	private RedisCache redisCache;
+	
+	private final String loginVerifyCodeKey = "loginVerifyCode:";
+	
+	private int expireTime = 60;
+
+	@Override
+	public boolean verifyValidCode(String mobile, String authCode) {
+		return true;
+	}
+
+	@Override
+	public boolean sendValidCode(String mobile) {
+		String code = RandomStringUtils.randomNumeric(6);
+		// 发送验证码
+		redisCache.put(loginVerifyCodeKey + mobile, code, expireTime);
+		return true;
+	}
+
+	@Override
+	public String getValidCode(String mobile) {
+		return (String) redisCache.get(loginVerifyCodeKey + mobile);
+	}
+
+	@Override
+	public void removeValidCode(String mobile) {
+		if (redisCache.exists(loginVerifyCodeKey + mobile)) {
+			redisCache.delete(loginVerifyCodeKey + mobile);
+		}
+	}
+
+}