This article introduces Spring Security Oauth2.0 to implement SMS verification code login examples, and share them with you, as follows:
Define mobile phone number login token
/** * @author length * @date 2018/1/9 * Mobile number login token*/public class MobileAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Object principal; public MobileAuthenticationToken(String mobile) { super(null); this.principal = mobile; setAuthenticated(false); } public MobileAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; super.setAuthenticated(true); } public Object getPrincipal() { return this.principal; } @Override public Object getCredentials() { return null; } public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated) { throw new IllegalArgumentException( "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); }}Mobile phone number login verification logic
/** * @author length * @date 2018/1/9 * Mobile number login verification logic*/public class MobileAuthenticationProvider implements AuthenticationProvider { private UserService userService; @Override public Authentication authentication(Authentication authentication) throws AuthenticationException { MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication; UserVo userVo = userService.findUserByMobile((String) mobileAuthenticationToken.getPrincipal()); UserDetailsImpl userDetails = buildUserDeatils(userVo); if (userDetails == null) { throw new InternalAuthenticationServiceException("Mobile number does not exist:" + mobileAuthenticationToken.getPrincipal()); } MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities()); authenticationToken.setDetails(mobileAuthenticationToken.getDetails()); return authenticationToken; } private UserDetailsImpl buildUserDeatils(UserVo userVo) { return new UserDetailsImpl(userVo); } @Override public boolean supports(Class<?> authentication) { return MobileAuthenticationToken.class.isAssignableFrom(authentication); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; }}Login process filter processing
/** * @author length * @date 2018/1/9 * Mobile number login verification filter */public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private boolean postOnly = true; public MobileAuthenticationFilter() { super(new AntPathRequestMatcher(SecurityConstants.MOBILE_TOKEN_URL, "POST")); } public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals(HttpMethod.POST.name()))) { throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); } String mobile = obtainMobile(request); if (mobile == null) { mobile = ""; } mobile = mobile.trim(); MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile); setDetails(request, mobileAuthenticationToken); return this.getAuthenticationManager().authenticate(mobileAuthenticationToken); } protected String obtainedMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected void setDetails(HttpServletRequest request, MobileAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public String getMobileParameter() { return mobileParameter; } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public boolean isPostOnly() { return postOnly; }}Production token location
/** * @author length * @date 2018/1/8 * The mobile phone number login is successful and returns oauth token */@Componentpublic class MobileLoginSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ObjectMapper objectMapper; @Autowired private ClientDetailsService clientDetailsService; @Autowired private AuthorizationServerTokenServices authorizationServerTokenServices; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Basic "))) { throw new UnapprovedClientAuthenticationException("Client information in the request header is empty"); } try { String[] tokens = extractAndDecodeHeader(header); assert tokens.length == 2; String clientId = tokens[0]; String clientSecret = tokens[1]; JSONObject params = new JSONObject(); params.put("clientId", clientId); params.put("clientSecret", clientSecret); params.put("authentication", authentication); ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile"); OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication); logger.info("Get token success: {}", oAuth2AccessToken.getValue()); response.setCharacterEncoding(CommonConstant.UTF8); response.setContentType(CommonConstant.CONTENT_TYPE); PrintWriter printWriter = response.getWriter(); printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken)); } catch (IOException e) { throw new BadCredentialsException( "Failed to decode basic authentication token"); } } /** * Decodes the header into a username and password. * * @throws BadCredentialsException if the Basic header is not present or is not valid * Base64 */ private String[] extractAndDecodeHeader(String header) throws IOException { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException e) { throw new BadCredentialsException( "Failed to decode basic authentication token"); } String token = new String(decoded, CommonConstant.UTF8); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } return new String[]{token.substring(0, delim), token.substring(delim + 1)}; }}Configure the above customization
//** * @author length * @date 2018/1/9 * Mobile number login configuration portal*/@Componentpublic class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private MobileLoginSuccessHandler mobileLoginSuccessHandler; @Autowired private UserService userService; @Override public void configure(HttpSecurity http) throws Exception { MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter(); mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler); MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider(); mobileAuthenticationProvider.setUserService(userService); http.authenticationProvider(mobileAuthenticationProvider) .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); }}The aggregate configuration that is specified above the spring security configuration
/** * @author length * @date January 9, 2018 14:01:25 * Authentication server open interface configuration*/@Configuration@EnableResourceServerpublic class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private FilterUrlsPropertiesConifg filterUrlsPropertiesConifg; @Autowired private MobileSecurityConfigurer mobileSecurityConfigurer; @Override public void configure(HttpSecurity http) throws Exception { registry .antMatchers("/mobile/token").permissionAll() .anyRequest().authenticated() .and() .csrf().disable(); http.apply(mobileSecurityConfigurer); }}use
The code copy is as follows:
curl -H "Authorization:Basic cGlnOnBpZw==" -d "grant_type=mobile&scope=server&mobile=17034642119&code=" http://localhost:9999/auth/mobile/token
Source code
Please refer to gitee.com/log4j/
Based on Spring Cloud and Spring Security Oauth2.0, enterprise-level authentication and authorization are developed, providing common service monitoring, link tracing, log analysis, cache management, task scheduling and other implementations
The entire logic is implemented in the usernamepassword login mode of spring security, and you can refer to its source code.
The logic of issuing and verification of verification codes is relatively simple. After the method, use the global fitter to determine whether the code in the request matches the mobile phone number. The key logic is the parameters of the token.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.