Browse Source

add 新增验证码登录,返回值处理

zouxuan 5 years ago
parent
commit
474aa5ed91
18 changed files with 359 additions and 73 deletions
  1. 11 0
      mec-auth/mec-auth-server/pom.xml
  2. 9 8
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/AuthorizationServerConfig.java
  3. 51 21
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/WebSecurityConfig.java
  4. 3 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/BaseUserDetailsService.java
  5. 36 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/SmsCodeAuthenticationProvider.java
  6. 36 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/provider/service/SmsUserDetailService.java
  7. 1 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/token/PhoneAuthenticationToken.java
  8. 28 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/SmsCodeController.java
  9. 6 5
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/BaseAuthenticationFilter.java
  10. 49 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/SmsCodeAuthenticationFilter.java
  11. 13 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/handler/BaseAuthenticationFailureEvenHandler.java
  12. 25 34
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/handler/BaseAuthenticationSuccessEventHandler.java
  13. 28 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/SmsCodeService.java
  14. 49 0
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/impl/SmsCodeServiceImpl.java
  15. 3 1
      mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/impl/SysUserServiceImpl.java
  16. 1 1
      mec-common/src/main/java/com/ym/mec/common/constant/CommonConstants.java
  17. 1 1
      mec-common/src/main/java/com/ym/mec/common/exception/BasicControllerAdvice.java
  18. 9 0
      pom.xml

+ 11 - 0
mec-auth/mec-auth-server/pom.xml

@@ -30,6 +30,12 @@
 		</dependency>
 
 		<dependency>
+			<groupId>org.springframework.social</groupId>
+			<artifactId>spring-social-core</artifactId>
+		</dependency>
+
+
+		<dependency>
 			<groupId>org.springframework.cloud</groupId>
 			<artifactId>spring-cloud-starter-security</artifactId>
 		</dependency>
@@ -58,6 +64,11 @@
 			<artifactId>mec-auth-api</artifactId>
 			<version>1.0</version>
 		</dependency>
+		<dependency>
+			<groupId>org.springframework.social</groupId>
+			<artifactId>spring-social-security</artifactId>
+			<version>1.1.6.RELEASE</version>
+		</dependency>
 
 	</dependencies>
 </project>

+ 9 - 8
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/AuthorizationServerConfig.java

@@ -1,9 +1,7 @@
 package com.ym.mec.auth.config;
 
-import javax.sql.DataSource;
-
+import com.ym.mec.common.constant.CommonConstants;
 import lombok.AllArgsConstructor;
-
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
@@ -17,8 +15,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 com.ym.mec.common.constant.CommonConstants;
+import javax.sql.DataSource;
 
 /**
  * 授权服务器配置
@@ -30,7 +27,6 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
 
 	@Autowired
 	private RedisConnectionFactory connectionFactory;
-
 	@Autowired
 	private AuthenticationManager authenticationManager;
 
@@ -39,12 +35,17 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
 
 	@Override
 	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
-		endpoints.authenticationManager(authenticationManager).tokenServices(defaultTokenServices());
+		endpoints
+				.authenticationManager(authenticationManager)
+				.tokenServices(defaultTokenServices())
+				.tokenStore(redisTokenStore());
 	}
 
 	@Override
 	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
-		security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();
+		security.tokenKeyAccess("isAuthenticated()")
+				.checkTokenAccess("permitAll()")
+				.allowFormAuthenticationForClients();
 	}
 
 	@Override

+ 51 - 21
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/config/WebSecurityConfig.java

@@ -1,9 +1,18 @@
 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;
@@ -14,10 +23,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
 import org.springframework.security.crypto.factory.PasswordEncoderFactories;
 import org.springframework.security.crypto.password.PasswordEncoder;
 
-import com.ym.mec.auth.config.provider.service.BaseUserDetailsService;
-import com.ym.mec.auth.filter.BaseAuthenticationFilter;
-import com.ym.mec.auth.handler.BaseAuthenticationFailureEvenHandler;
-import com.ym.mec.auth.handler.BaseAuthenticationSuccessEventHandler;
+import java.util.Arrays;
 
 @Configuration
 @EnableWebSecurity
@@ -26,6 +32,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
 	@Autowired
 	private BaseUserDetailsService baseUserDetailsService;
+	@Autowired
+	private SmsCodeAuthenticationProvider smsCodeAuthenticationProvider;
+	@Autowired
+	private BaseAuthenticationSuccessEventHandler successEventHandler;
+	@Autowired
+	private BaseAuthenticationFailureEvenHandler failureEvenHandler;
+	@Autowired
+	private BaseAccessDeniedHandler baseAccessDeniedHandler;
+	@Autowired
+	private BaseAuthenticationEntryPoint baseAuthenticationEntryPoint;
 
 	@Override
 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
@@ -34,32 +50,38 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
 	@Override
 	protected void configure(HttpSecurity http) throws Exception {
-
 		// 表单登录 方式
 		http
-		// .addFilterAt(getBaseAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
-		.formLogin().loginPage("/loginIn").and()
-		// 请求授权
-				.authorizeRequests()
-				// 不需要权限认证的url
-				.antMatchers("/oauth/**").permitAll()
-				// 任何请求
-				.anyRequest()
-				// 需要身份认证
-				.authenticated().and()
-				// 关闭跨站请求防护
-				.csrf().disable();
+				.formLogin()
+				.loginPage("/loginIn")
+				.loginPage("/smsLogin")
+				.successHandler(successEventHandler)
+				.failureHandler(failureEvenHandler)
+			.and()
+				.exceptionHandling()
+				.accessDeniedHandler(baseAccessDeniedHandler)
+				.authenticationEntryPoint(baseAuthenticationEntryPoint)// 当未登录访问资源时
+			.and()// 请求授权
+				.authorizeRequests()// 不需要权限认证的url
+				.antMatchers("/oauth/**").permitAll()// 任何请求
+				.anyRequest()// 需要身份认证
+				.authenticated()
+			.and()// 关闭跨站请求防护
+				.csrf()
+				.disable();
 	}
 
 	@Override
 	public void configure(WebSecurity web) throws Exception {
-		web.ignoring().antMatchers("/loginIn", "/refreshToken","/v2/api-docs");
+		web.ignoring().antMatchers("/loginIn","/smsLogin", "/refreshToken","/v2/api-docs");
 	}
 
 	@Bean
 	@Override
 	public AuthenticationManager authenticationManagerBean() throws Exception {
-		return super.authenticationManagerBean();
+		ProviderManager authenticationManager = new ProviderManager(Arrays.asList(smsCodeAuthenticationProvider,daoAuthenticationProvider()));
+		authenticationManager.setEraseCredentialsAfterAuthentication(false);
+		return authenticationManager;
 	}
 
 	@Bean
@@ -83,8 +105,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 	public BaseAuthenticationFilter getBaseAuthenticationFilter() throws Exception {
 		BaseAuthenticationFilter filter = new BaseAuthenticationFilter();
 		filter.setAuthenticationManager(authenticationManagerBean());
-		filter.setAuthenticationSuccessHandler(new BaseAuthenticationSuccessEventHandler());
-		filter.setAuthenticationFailureHandler(new BaseAuthenticationFailureEvenHandler());
+		filter.setAuthenticationSuccessHandler(successEventHandler);
+		filter.setAuthenticationFailureHandler(failureEvenHandler);
+		return filter;
+	}
+	@Bean
+	public SmsCodeAuthenticationFilter getSmsCodeAuthenticationFilter() throws Exception {
+		SmsCodeAuthenticationFilter filter = new SmsCodeAuthenticationFilter();
+		filter.setAuthenticationManager(authenticationManagerBean());
+		filter.setAuthenticationSuccessHandler(successEventHandler);
+		filter.setAuthenticationFailureHandler(failureEvenHandler);
 		return filter;
 	}
 

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

@@ -30,6 +30,9 @@ public class BaseUserDetailsService implements UserDetailsService {
 
 	@Override
 	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+		if(StringUtils.isBlank(username)){
+			return null;
+		}
 
 		SysUserInfo userInfo = sysUserService.queryUserInfoByUsername(username);
 

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

@@ -0,0 +1,36 @@
+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);
+    }
+}

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

@@ -0,0 +1,36 @@
+package com.ym.mec.auth.config.provider.service;
+
+import com.ym.mec.auth.api.dto.SysUserInfo;
+import com.ym.mec.auth.api.entity.SysUser;
+import com.ym.mec.auth.service.SysUserService;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.AuthorityUtils;
+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.stereotype.Service;
+import java.util.List;
+
+@Service
+public class SmsUserDetailService implements UserDetailsService {
+
+    @Autowired
+    private SysUserService sysUserService;
+
+    @Override
+    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
+        SysUserInfo userInfo = sysUserService.queryUserInfoByPhone(phone);
+        if(userInfo == null){
+            return null;
+        }
+        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(userInfo.getPermissions());
+
+        SysUser sysUser = userInfo.getSysUser();
+
+        return new User(phone, "", StringUtils.equals(sysUser.getLockFlag(), "0"), true, true, true,
+                authorities);
+    }
+}

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

@@ -13,7 +13,7 @@ public class PhoneAuthenticationToken extends AbstractAuthenticationToken {
 	private static final long serialVersionUID = 110L;
 	private final Object principal;
 
-	public PhoneAuthenticationToken(String mobile) {
+	public PhoneAuthenticationToken(Object mobile) {
 		super(null);
 		this.principal = mobile;
 		setAuthenticated(false);

+ 28 - 0
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/controller/SmsCodeController.java

@@ -0,0 +1,28 @@
+package com.ym.mec.auth.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;
+
+@RestController
+@RequestMapping("sms")
+@Api(description = "短信服务")
+public class SmsCodeController extends BaseController {
+
+    @Autowired
+    private SmsCodeService smsCodeService;
+
+    @ApiOperation("发送登录短信验证码")
+    @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String")
+    @PostMapping("/sendVerifyCode")
+    public Object sendLoginVerifyCode(String mobile) {
+        smsCodeService.sendLoginVerifyCode(mobile);
+        return succeed();
+    }
+}

+ 6 - 5
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/filter/BaseAuthenticationFilter.java

@@ -1,8 +1,5 @@
 package com.ym.mec.auth.filter;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
 import org.springframework.security.authentication.AuthenticationServiceException;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
@@ -11,6 +8,9 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro
 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 import org.springframework.util.Assert;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
 public class BaseAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
 
 	// ~ Static fields/initializers
@@ -24,14 +24,15 @@ public class BaseAuthenticationFilter extends AbstractAuthenticationProcessingFi
 	// ===================================================================================================
 
 	public BaseAuthenticationFilter() {
-		super(new AntPathRequestMatcher("/login", "POST"));
+		super(new AntPathRequestMatcher("/loginIn", "POST"));
 	}
 
 	// ~ Methods
 	// ========================================================================================================
 
+
 	public Authentication attemptAuthentication(HttpServletRequest request,
-			HttpServletResponse response) throws AuthenticationException {
+												HttpServletResponse response) throws AuthenticationException {
 		if (postOnly && !request.getMethod().equals("POST")) {
 			throw new AuthenticationServiceException(
 					"Authentication method not supported: " + request.getMethod());

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

@@ -0,0 +1,49 @@
+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.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
+import org.springframework.security.web.access.ExceptionTranslationFilter;
+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);
+    }
+}

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

@@ -6,13 +6,22 @@ import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ym.mec.common.entity.HttpResponseResult;
+import org.apache.http.HttpStatus;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
+import org.springframework.stereotype.Component;
 
+@Component
 public class BaseAuthenticationFailureEvenHandler extends ExceptionMappingAuthenticationFailureHandler {
 
+	@Autowired
+	private ObjectMapper objectMapper;
+
 	private final static Logger logger = LoggerFactory.getLogger(BaseAuthenticationFailureEvenHandler.class);
 
 	@Override
@@ -22,6 +31,9 @@ public class BaseAuthenticationFailureEvenHandler extends ExceptionMappingAuthen
 		Object username = request.getAttribute("SPRING_SECURITY_LAST_USERNAME_KEY");
 
 		logger.info("用户:{} 登录失败,异常:{}", username, authenticationException.getLocalizedMessage());
-		super.onAuthenticationFailure(request, response, authenticationException);
+		HttpResponseResult result = new HttpResponseResult(false, HttpStatus.SC_CONFLICT, null, authenticationException.getLocalizedMessage());
+		response.setContentType("application/json; charset=utf-8");
+		response.getWriter().write(objectMapper.writeValueAsString(result));
+//		super.onAuthenticationFailure(request, response, authenticationException);
 	}
 }

+ 25 - 34
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/handler/BaseAuthenticationSuccessEventHandler.java

@@ -1,34 +1,31 @@
 package com.ym.mec.auth.handler;
 
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Base64;
-import java.util.HashMap;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ym.mec.common.entity.HttpResponseResult;
+import org.apache.commons.collections.MapUtils;
 import org.apache.http.HttpStatus;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
 import org.springframework.security.authentication.BadCredentialsException;
 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.*;
 import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
 import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
 
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.ym.mec.common.constant.CommonConstants;
-import com.ym.mec.common.entity.HttpResponseResult;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Base64;
 
+@Component
 public class BaseAuthenticationSuccessEventHandler extends SavedRequestAwareAuthenticationSuccessHandler {
 
 	private final static Logger logger = LoggerFactory.getLogger(BaseAuthenticationSuccessEventHandler.class);
@@ -46,35 +43,29 @@ public class BaseAuthenticationSuccessEventHandler extends SavedRequestAwareAuth
 	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException,
 			IOException {
 		logger.info("用户:{} 登录成功", authentication.getPrincipal());
-
-		String header = request.getHeader("Authorization");
-
-		if (header == null || !header.startsWith(CommonConstants.BASIC)) {
-			throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
-		}
-
 		try {
-			String[] tokens = extractAndDecodeHeader(header);
-			String clientId = tokens[0];
-			// String clientSecret = tokens[1];
+			String clientId = request.getParameter("clientId");
+			String clientSecret = request.getParameter("clientSecret");
+			if (clientId == null || clientSecret == null) {
+				throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
+			}
+			String base64ClientCredentials = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
+			HttpHeaders headers = new HttpHeaders();
+			headers.add("Authorization", "Basic " + base64ClientCredentials);
+			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
 			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
-			TokenRequest tokenRequest = new TokenRequest(new HashMap<String, String>(), clientId, clientDetails.getScope(), "password");
+			TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "password");
 			OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
 
 			OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
 			OAuth2AccessToken oAuth2AccessToken = defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication);
 			logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
 
-			response.setCharacterEncoding("utf-8");
 			response.setContentType("application/json; charset=utf-8");
-			PrintWriter printWriter = response.getWriter();
 
 			HttpResponseResult result = new HttpResponseResult(true, HttpStatus.SC_OK, oAuth2AccessToken, "");
-
-			printWriter.append(objectMapper.writeValueAsString(result));
-			printWriter.flush();
-			printWriter.close();
+			response.getWriter().write(objectMapper.writeValueAsString(result));
 		} catch (IOException e) {
 			throw new BadCredentialsException("Failed to decode basic authentication token");
 		}

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

@@ -0,0 +1,28 @@
+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);
+}

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

@@ -0,0 +1,49 @@
+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;
+    }
+}

+ 3 - 1
mec-auth/mec-auth-server/src/main/java/com/ym/mec/auth/service/impl/SysUserServiceImpl.java

@@ -67,7 +67,9 @@ public class SysUserServiceImpl extends BaseServiceImpl<Integer, SysUser> implem
 		SysUserInfo userInfo = new SysUserInfo();
 
 		SysUser sysUser = queryByPhone(phone);
-
+		if(sysUser == null){
+			return null;
+		}
 		userInfo.setSysUser(sysUser);
 
 		List<Integer> roleIdList = sysUserRoleService.queryRoleIdListByUserId(sysUser.getUserId());

+ 1 - 1
mec-common/src/main/java/com/ym/mec/common/constant/CommonConstants.java

@@ -15,7 +15,7 @@ public interface CommonConstants {
 	/**
 	 * oauth 相关前缀
 	 */
-	String OAUTH_PREFIX = "oauth:";
+	String OAUTH_PREFIX = "access:";
 
 	String BASIC = "Basic ";
 

+ 1 - 1
mec-common/src/main/java/com/ym/mec/common/exception/BasicControllerAdvice.java

@@ -40,7 +40,7 @@ public class BasicControllerAdvice extends BaseController {
 		}
 
 		logger.error("System Error", e);
-		return failed("系统繁忙");
+		return failed(e.getMessage());
 	}
 
 }

+ 9 - 0
pom.xml

@@ -91,6 +91,11 @@
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-actuator</artifactId>
 		</dependency>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-test</artifactId>
+			<scope>test</scope>
+		</dependency>
 		
 		<!-- SpringBoot整合config组件 -->
 		<!-- <dependency>
@@ -112,6 +117,10 @@
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-security</artifactId>
 		</dependency>
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+		</dependency>
 		
 		<!--集群监控消息队列 -->
 		<!-- <dependency>