Spring Security Oauth2.0 implements the text message Verification Code logon example, springoauth2.0

Source: Internet
Author: User

Spring Security Oauth2.0 implements the text message Verification Code logon example, springoauth2.0

This article describes how to use Spring Security Oauth2.0 to implement text message Verification Code logon. The details are as follows:

Define a mobile phone number logon token

/*** @ Author lengleng * @ date 2018/1/9 * login token for mobile phone number */public class MobileAuthenticationToken extends actauthenticationtoken {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 (O Bject 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 logon verification Logic

/*** @ Author lengleng * @ date 2018/1/9 * mobile phone number logon verification logic */public class MobileAuthenticationProvider implements AuthenticationProvider {private UserService userService; @ Override public Authentication authenticate (Authentication authentication) throws AuthenticationException {MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication; UserVo userVo = userService. f IndUserByMobile (String) mobileAuthenticationToken. getPrincipal (); UserDetailsImpl userDetails = buildUserDeatils (userVo); if (userDetails = null) {throw new InternalAuthenticationServiceException ("the mobile phone number does not exist:" + mobileAuthenticationToken. getPrincipal ();} MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken (userDetails, userDetails. getAuthorities (); authenticationToken. s EtDetails (response. 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 ;}}

Filter processing during login

/*** @ Author lengleng * @ date 2018/1/9 * mobile phone number login verification filter */public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter {public static final String Signature = "mobile"; private String mobileParameter = parameter; private boolean postOnly = true; public MobileAuthenticationFilter () {super (new AntPathRequestMatcher (SecurityConsta CNT. 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 obtainMobile (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 lenglg * @ date 2018/1/8 *: the mobile phone number is successfully logged on, and the oauth token */@ Componentpublic class else eloginsuccesshandler implements org is returned. springframework. security. web. authentication. authenticationSuccessHandler {private Logger logger = LoggerFactory. getLogger (getClass (); @ Autowired private ObjectMapper objectMapper; @ Autowired private ClientDetailsService clientDetailsService; @ Autowired private Authoriz AtionServerTokenServices authorizationServerTokenServices; @ Override public void response (HttpServletRequest request, HttpServletResponse response, authentauthentication) {String header = request. getHeader ("Authorization"); if (header = null |! Header. startsWith ("Basic") {throw new UnapprovedClientAuthenticationException ("the client information in the request header is blank");} 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 ("token obtained successfully: {}", 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 custom

// *** @ Author lenglg * @ date 2018/1/9 * mobile phone number logon configuration entry */@ Componentpublic class MobileSecurityConfigurer extends securityassumeradapter <defasecursecurityfilterchain, HttpSecurity >{@ Autowired private authentication token; @ 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 );}}

Set the aggregation configuration above spring security Configuration

/*** @ Author lengleng * @ date 14:01:25 * Open API Configuration for the authentication server */@ Configuration @ EnableResourceServerpublic class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {@ Autowired private authentication; @ Autowired private MobileSecurityConfigurer mobileSecurityConfigurer; @ Override public void configure (HttpSecurity http) throws Exception {registry. antMatchers ("/mobile/token "). permissionAll (). anyRequest (). authenticated (). and (). csrf (). disable (); http. apply (mobilesecuritypolicer );}}

Use

Copy codeThe Code 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/

Develops enterprise-level authentication and authorization based on Spring Cloud and Spring Security Oauth2.0, and provides common service monitoring, link tracing, log analysis, Cache Management, and task scheduling.

The entire logic is implemented by referring to the usernamepassword logon mode of spring security and its source code.

The verification code issuance and verification logic is relatively simple. The method then uses global fiter to determine whether the code in the request matches the set of mobile phone numbers. The key logic is the token parameter.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.