Artikel ini memperkenalkan OAuth2.0 Spring Security untuk mengimplementasikan contoh login kode verifikasi SMS, dan membaginya dengan Anda, sebagai berikut:
Tentukan token login nomor ponsel
/** * @author length * @Date 2018/1/9 * Nomor ponsel Token Login */Kelas Publik MobileAuthenticationToken memperluas abstractAuthenticationToken {private static final long serialversionuid = springsecuritycoreversion.serial_version_uid; Kepala Sekolah Objek Akhir Pribadi; Public MobileAuthenticationToken (String Mobile) {super (null); this.principal = seluler; setauthenticated (false); } public MobileAuthenticationToken (Object Principal, Collection <? Extends Grantedauthority> Otoritas) {super (otoritas); this.principal = prinsipal; super.setAuthenticated (true); } objek publik getPrincipal () {return this.principal; } @Override objek publik getCredentials () {return null; } public void setAuthenticated (boolean isAuthenticated) melempar ilegalargumentException {if (isAuthenticated) {melempar baru ilegalargumentException ("tidak dapat mengatur token ini ke konstruktor yang dipercaya - gunakan yang mengambil daftar yang diberikan sebagai gantinya"); } super.setAuthenticated (false); } @Override public void erasecredentials () {super.erasecredentials (); }}Logika Verifikasi Login Nomor Ponsel
/** * @author length * @date 2018/1/9 * Nomor ponsel Logika verifikasi Login */Kelas Publik MobileAuthenticationProvider mengimplementasikan AuthenticationProvider {private UserServerServiceService; @Override Otentikasi Publik Otentikasi (Otentikasi Otentikasi) Melemparkan OtenticationException {MobileAuthenticationToken MobileAuthenticationToken = (MobileAuthenticationToken) otentikasi; UserVo userVo = Userservice.finduserbyMobile ((string) calonAuthenticationToken.getPrincipal ()); UserDetailSimpl userDetails = buildUserDeatils (USERVO); if (userDetails == null) {lempar internalAuthenticationServiceException baru ("Nomor ponsel tidak ada:" + mobileAuthenticationToken.getPrincipal ()); } MobileAuthenticationToken authenticationToken = MobileAuthenticationToken baru (userDetails, userDetails.getauthority ()); authenticationToken.setDetails (MobileAuthenticationToken.getDetails ()); Return AuthenticationToken; } private userDetailSimpl buildeSerDeatils (userVo userVo) {return new userDetailSimpl (userVo); } @Override Public Boolean Dukungan (kelas <?> Otentikasi) {return mobileAuthenticationToken.class.isassignableFrom (otentikasi); } Public UserService getUserService () {Return UserService; } public void setUsersERVICE (UserserService Userservice) {this.userservice = UserserService; }}Pemrosesan filter proses login
/** * @author length * @date 2018/1/9 * Nomor ponsel Filter verifikasi login */kelas publik mobileAuthenticationFilter memperluas abstractAuthenticationProcessingFilter {public static final string final spring_security_form_mobile_key = "seluler"; Private String MobileParameter = spring_security_form_mobile_key; Private Boolean Postonly = true; Public MobileAuthenticationFilter () {super (antpathrequestmatcher baru (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 = ESTECTMOBILE (permintaan); if (seluler == null) {Mobile = ""; } Mobile = Mobile.trim (); MobileAuthenticationToken MobileAuthenticationToken = MobileAuthenticationToken (Mobile) baru; setDetails (permintaan, mobileAuthenticationToken); kembalikan this.getAuthenticationManager (). Otentikasi (MobileAuthenticationToken); } string protected yang diperoleh Mobile (permintaan httpservletRequest) {return request.getParameter (MobileParameter); } lindung void setDetails (permintaan httpservletRequest, mobileAuthenticationToken authRequest) {authRequest.setDetails (authenticationDetailssource.builddetails (permintaan)); } 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; }}Lokasi token produksi
/** * @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 OtorisasiServertokenServices; @Override public void onAuthenticationsuccess (permintaan httpservletRequest, respons httpservletResponse, otentikasi otentikasi) {string header = request.getHeader ("otorisasi"); if (header == null ||! header.startswith ("basic"))) {lempar baru yang tidak disetujuiClientAuthenticationException ("Informasi klien di header permintaan kosong"); } coba {string [] tokens = extractAndDecodeHeader (header); Assert Tokens.Length == 2; String clientId = token [0]; String clientsecret = token [1]; JsonObject params = new jsonObject (); params.put ("clientId", clientId); params.put ("ClientSecret", ClientSecret); params.put ("otentikasi", otentikasi); ClientDetails clientDetails = clientDetailsService.LoadClientByClientId (clientId); TokenRequest tokenRequest = new tokenRequest (maputil.newhashmap (), clientId, clientdetails.getscope (), "seluler"); OAuth2Request oAuth2Request = TokenRequest.CreateOAuth2Request (ClientDetails); OAuth2Authentication oAuth2Authentication = OAuth2Authentication baru (OAuth2Request, Authentication); OAuth2AccessToken oAuth2AccessToken = otorisasiServertokenservices.createaccesstoken (oauth2authentication); logger.info ("Dapatkan 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) {lempar new badcredentialsException ("Gagal memecahkan kode token otentikasi dasar"); }} /*** Decodes header menjadi nama pengguna dan kata sandi. * * @throws BadCredentialSException Jika header dasar tidak ada atau tidak valid * base64 */ private string [] extractAndDecodeHeader (header string) melempar ioException {byte [] base64Token = header.substring (6) .getbytes ("utf-8"); byte [] diterjemahkan; coba {decoded = base64.decode (base64token); } catch (IllegalArgumentException e) {lempar new badcredentialsException ("Gagal memecahkan kode token otentikasi dasar"); } String token = string baru (decoded, commonconstant.utf8); int delim = token.indexof (":"); if (delim == -1) {lempar badcredentialsException baru ("token otentikasi dasar yang tidak valid"); } return string baru [] {token.substring (0, delim), token.substring (delim + 1)}; }}Konfigurasikan kustomisasi di atas
// ** * @author length * @Date 2018/1/9 * Portal Konfigurasi Login Nomor Ponsel */ @ComponentPublic Class MobileSecurityConfigurer Memperluas SecurityConfigurerAdapter <DefaultSecurityFilterChain, httpsecurity> @Autowired swasta MobileLelogInclerLerler, httpsecurity> @Autowired private MobileLelogInclerlerer, httpsecurity> @Autowired private MobileLeloginshandlerller; @Autowired Private UserServerServiceService; @Override public void configure (httpsecurity http) melempar Exception {MobileAuthenticationFilter MobileAuthenticationFilter = MobileAuthenticationFilter baru (); MobileAuthenticationFilter.SetAuthenticationManager (http.getsharedObject (authenticationManager.class)); MobileAuthenticationFilter.SetAuthenticationsuccesshandler (Mobileloginsuccesshandler); MobileAuthenticationProvider MobileAuthenticationProvider = new MobileAuthenticationProvider (); MobileAuthenticationProvider.SetUserservice (Userservice); http.authenticationProvider (mobileAuthenticationProvider) .addfilterAfter (MobileAuthenticationFilter, UsernamepasswordAuthenticationFilter.class); }}Konfigurasi agregat yang ditentukan di atas konfigurasi keamanan pegas
/** * @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) melempar Exception {registry .AntMatchers ("/Mobile/Token"). IzinAll () .AnyRequest (). Authenticated () .and () .csrf (). Disable (); http.Apply (MobileSecurityConfigurer); }}menggunakan
Salinan kode adalah sebagai berikut:
Curl -H "Otorisasi: CGLNONBPZW BASIC ==" -D "hAND_TYPE = MOBILE & SCOPE = Server & Mobile = 17034642119 & Code =" http: // localhost: 9999/auth/seluler/token
Kode Sumber
Silakan merujuk ke gitee.com/log4j/
Berdasarkan Spring Cloud dan Spring Security OAuth2.0, otentikasi dan otorisasi tingkat perusahaan dikembangkan, menyediakan pemantauan layanan umum, penelusuran tautan, analisis log, manajemen cache, penjadwalan tugas dan implementasi lainnya
Seluruh logika diimplementasikan dalam mode login UserNamepassword dari keamanan musim semi, dan Anda dapat merujuk pada kode sumbernya.
Logika penerbitan dan verifikasi kode verifikasi relatif sederhana. Setelah metode ini, gunakan Global Fitter untuk menentukan apakah kode dalam permintaan cocok dengan nomor ponsel. Logika kunci adalah parameter token.
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.