Cet article présente Spring Security OAuth2.0 pour implémenter des exemples de connexion du code de vérification SMS et les partager avec vous, comme suit:
Définir le jeton de connexion du numéro de téléphone mobile
/ ** * @Author Length * @Date 2018/1/9 * Numéro de mobile Token * / classe publique MobileAuthenticationToken étend AbstractAuthenticationToken {private statique final long SerialVersionUid = springSecurityCoreversion.Serial_version_Uid; Principal d'objet final privé; public mobileAuthenticationToken (String mobile) {super (null); this.principal = mobile; setAuthenticated (false); } public MobileAuthenticationToken (directeur d'objet, collection <? étend l'autorité accorde> autorités) {super (autorités); this.principal = principal; super.setAuthenticated (true); } objet public getPrincipal () {return this.principal; } @Override public objet getCredentials () {return null; } public void setAuthenticated (boolean isAuthenticated) lève illégalArgumentException {if (isAuthenticated) {lancez un nouveau constructeur illégalargumentException ("ne peut pas définir ce jeton de confiance - utilisez le constructeur qui prend une liste d'autorité accordé à la place"); } super.setAuthenticated (false); } @Override public void erasecredentials () {super.erasecredentials (); }}Numéro de téléphone mobile Logique de vérification de connexion
/ ** * @Author Length * @Date 2018/1/9 * Numéro de mobile Logique de vérification de connexion * / classe publique MobileAuthenticationProvider implémente AuthenticationProvider {Private UserService UserService; @Override Authentification de l'authentification publique (authentification Authentification) lève AuthenticationException {MobileAuthenticationToken MobileAuthenticationToken = (MobileAuthenticationToken) Authentification; UserVo userVo = userService.FindUserByMobile ((String) mobileAuthenticationToken.getPrincipal ()); UserDetailSIMPL UserDetails = BuildUserDeatils (USERVO); if (userDetails == null) {lancez de nouveaux AuthenticationsServiceException ("Le numéro de mobile n'existe pas:" + mobileAuthenticationToken.getPrincipal ()); } MobileAuthenticationToken AuthenticationToken = new MobileAuthenticationToken (UserDetails, userDetails.GetAuthorities ()); authenticationToken.setDetails (mobileAuthenticationToken.getDetails ()); Retour AuthenticationToken; } UserDeTailSIMPLIMPLIMP BUILDUSERDEATILS (USERVO USERVO) {RETOUR NOUVEAU USERDETAILSIMPL (USERVO); } @Override public booléen supports (class <?> Authentication) {return mobileAuthenticationToken.class.isassignableFrom (authentification); } public userService getUserService () {return userService; } public void SetUserService (UserService UserService) {this.UserService = UserService; }}Traitement du filtre du processus de connexion
/ ** * @Author Length * @Date 2018/1/9 * Numéro de mobile Filtre de vérification de connexion * / classe publique MobileAuthenticationFilter étend AbstractAuthenticationProcessingFilter {public static final String Spring_Security_Form_Mobile_Key = "Mobile"; chaîne privée mobileParameter = spring_security_form_mobile_key; Boolean privé postonly = true; public mobileAuthenticationFilter () {super (new antpathrequestmatcher (SecurityConstants.mobile_token_url, "post")); } Public Authentication Tentient Authentication (demande HttpServletRequest, réponse httpservletResponse) lève AuthenticationException {if (postonly &&! request.getMethod (). Equals (httpMethod.post.name ()))) {lancez new AuthenticationsServiceException ("Method Authentication Method Not SupportEd:" + requête. } String mobile = obttepmobile (request); if (mobile == null) {mobile = ""; } mobile = mobile.trim (); MobileAuthenticationToken MobileAuthenticationToken = new MobileAuthenticationToken (mobile); setDetails (demande, mobileAuthenticationToken); Renvoie ce.getAuthenticationManager (). Authenticiate (MobileAuthenticationToken); } chaîne protégée obtenuemobile (requette httpServleRequest) {return request.getParameter (mobileParameter); } Protected void setDetails (requette httpServleRequest, mobileAuthenticationToken AuthRequest) {Authrequest.SetDetails (authenticationDetailsSource.buildDetails (requête)); } public void setpostonly (boolean postonly) {this.postonly = postonly; } public String getMobileParameter () {return mobileParAmètre; } public void setMobileParameter (String mobileParameter) {this.mobileParameter = mobileParameter; } public boolean ispostonly () {return Postonly; }}Emplacement de jeton de production
/ ** * @Author Length * @Date 2018/1/8 * La connexion du numéro de téléphone mobile est réussie et renvoie un jet de token * / @ ComponentPublic MobileLoginsuccessHandler implémente org.springframework.Security.web.authentication.getLogger (GetClass); @Autowired Private ObjectMapper ObjectMapper; @Autowired private ClientDetailSService ClientDetailSService; @Autowired Private AutorisationserververtOKenServices AuthorizationservertokenServices; @Override public void onAuthenticationsUCCESS (demande httpservletRequest, réponse httpservletResponse, authentification authentification) {string header = request.getheader ("autorisation"); if (en-tête == null ||! header.startswith ("Basic")) {Throw New UnapprovedClientAuthenticationException ("Les informations du client dans l'en-tête de demande sont vides"); } try {String [] tokens = extractAndDodeHeader (en-tête); affirmer tokens.length == 2; String clientId = tokens [0]; String clientCret = tokens [1]; JsonObject Params = new JSONObject (); Params.put ("clientId", clientId); Params.put ("ClientsCret", ClientsCret); Params.put ("authentification", authentification); ClientDetails ClientDetails = clientTailsService.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 = AuthoriseServertokenServices.CreateAccessToken (OAuth2Authentication); Logger.info ("Get token Success: {}", oAuth2AccessToken.getValue ()); Response.SetcharAtterencoding (CommonConstant.Utf8); réponse.setContentType (CommonConstant.Content_type); Printwriter printwriter = réponse.getWriter (); printwriter.append (objectMapper.WriteValueAsString (oAuth2AccessToken)); } catch (ioException e) {Throw New BadCredentialSException ("Échec du décodage de token d'authentification de base"); }} / ** * Décode l'en-tête dans un nom d'utilisateur et un mot de passe. * * @Throws BadCredentialSException Si l'en-tête de base n'est pas présent ou n'est pas valide * Base64 * / Private String [] ExtractAndDecodeHeader (String Header) lève IoException {Byte [] Base64Token = header.SubString (6) .getBytes ("utf-8"); octet [] décodé; try {decoded = base64.decode (base64Token); } catch (illégalArgumentException e) {Throw New BadCredentialSexception ("Échec du décodage de token d'authentification de base"); } 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)}; }}Configurer la personnalisation ci-dessus
// ** * @Author Length * @Date 2018/1/9 * Numéro de mobile Portail de configuration de connexion * / @ ComponentPublic Class MobileSecurityConfigurer étend SecurityConfigurerAdapter <DefaultSecurityFilterChain, httpSeCurity> {@Autowired Private MobileLoLogInCesShandler MobileLoLogInsucCessHessHed; @Autowired Private UserService UserService; @Override public void configure (httpSecurity http) lève une 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); }}La configuration agrégée spécifiée au-dessus de la configuration de sécurité à ressort
/ ** * @Author Length * @Date 9 janvier 2018 14:01:25 * Configuration de l'interface ouverte du serveur d'authentification * / @ configuration @ enableResourceServerPublic Class ResourceServerConfiguration Extend ResourcesserverConfigurerAdapter {@Autowired Private FilterUrlSpropertiesConifg FilterlSpropertiesConifg; @Autowired Private MobileSecurityConfigurer MobileSecurityConfigurer; @Override public void configure (httpSecurity http) lève une exception {registre .antmatchers ("/ mobile / token"). Permissionall () .anyRequest (). Authenticated () .and () .csrf (). Disable (); http.apply (mobilesecurityconfigurer); }}utiliser
La copie de code est la suivante:
CURL -H "Autorisation: Basic CGlNonBPZW ==" -d "Grant_Type = Mobile & Scope = Server & Mobile = 17034642119 & Code =" http: // localhost: 9999 / auth / mobile / token
Code source
Veuillez vous référer à gitee.com/log4j/
Sur la base de Spring Cloud et Spring Security OAuth2.0, l'authentification et l'autorisation au niveau de l'entreprise sont développées, fournissant une surveillance des services communs, un traçage des liens, une analyse des journaux, une gestion du cache, une planification des tâches et d'autres implémentations
La logique entière est implémentée dans le mode de connexion UserNamePassword de la sécurité de Spring, et vous pouvez vous référer à son code source.
La logique de l'émission et de la vérification des codes de vérification est relativement simple. Après la méthode, utilisez le monteur global pour déterminer si le code de la demande correspond au numéro de téléphone mobile. La logique clé est les paramètres du jeton.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.