이 기사는 SMS 검증 코드 로그인 예제를 구현하기 위해 Spring Security OAUTH2.0을 소개하고 다음과 같이 다음과 같이 공유합니다.
휴대폰 번호 로그인 토큰을 정의하십시오
/** * @Author 길이 * @Date 2018/1/9 * 휴대 전화 번호 로그인 토큰 */공개 클래스 MobileAuthenticationToken 확장 {private static final long serialversionUid = springsecurityCoreVersion.serial_version_uid; 개인 최종 대상 교장; public mobileAuthenticationToken (String Mobile) {super (null); this.principal = 모바일; setAuthenticated (false); } public mobileAuthenticationToken (Object Principal, Collection <? extends granteAuthority> 당국) {Super (당국); this.principal = 교장; super.setAuthenticated (true); } public Object getPrincipal () {return this.principal; } @override public object getCredentials () {return null; } public void setAuthenticated (부울 isauthenticated)는 불법 행위 값을 던진다. {if (iSauthenticated) {새로운 불법 불법 행위 exception ( "이 토큰을 신뢰할 수있는 것으로 설정할 수 없다 - 대신 당연한 목록을 취하는 생성자"); } super.setAuthenticated (false); } @override public void EraseCredentials () {super.erasecredentials (); }}휴대 전화 번호 로그인 확인 논리
/** * @Author 길이 * @Date 2018/1/9 * 휴대폰 번호 로그인 검증 로직 */공개 클래스 MobileAuthenticationProvider는 AuthenticationProvider {private userservice userservice; @override public authentication authentication (인증 인증) authenticationException {mobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) 인증; uservo uservo = userervice.finduserbymobile ((String) mobileAuthenticationToken.getPrincipal ()); userDetailSimpl userDetails = buildUserDeatils (uservo); if (userDetails == null) {새로운 내부 AuthenticationServiceException ( "휴대 전화 번호가 존재하지 않습니다 :" + mobileAuthenticationToken.getPrincipal ()); } mobileAuthenticationToken AuthenticationToken = New MobileAuthenticationToken (userDetails, userDetails.getAuthorities ()); AuthenticationToken.setDetails (mobileAuthenticationToken.getDetails ()); AuthenticationToken 반환; } private userDetailSimpl buildUserDeatils (uservo uservo) {return new userDetailSimpl (uservo); } @override public boolean supports (class <?> 인증) {return mobileAuthenticationToken.class.isAssignableFrom (인증); } public userErvice getUserService () {return userErvice; } public void setUserService (userErvice userErvice) {this.userService = userErvice; }}프로세스 필터 처리 로그인
/** * @Author 길이 * @Date 2018/1/9 * 휴대폰 번호 로그인 검증 필터 */public class mobileAuthenticationFilter 확장 AbstractAuthenticationProcessingFilter {public static string spring_security_form_kobile_key = "mobile"; 개인 문자열 mobileparameter = spring_security_form_mobile_key; 개인 부울 postonly = true; Public MobileAuthenticationFilter () {Super (New AntpathRequestMatcher (SecurityConstants.Mobile_Token_url, "Post")); } 공개 인증 시도 시도 (httpservletRequest 요청, httpservletResponse 응답)는 authenticationException {if (postonly &&! request.getMethod (). } 문자열 mobile = acemobile (요청); if (mobile == null) {mobile = ""; } mobile = mobile.trim (); MobileAuthenticationToken MobileAuthenticationToken = New MobileAuthenticationToken (모바일); setDetails (요청, MobileAuthenticationToken); reture this.getAuthenticationManager (). 인증 (mobileAuthenticationToken); } 보호 된 문자열 augeDmobile (httpservletrequest request) {return request.getParameter (mobileparameter); } 보호 된 void setDetails (httpservletRequest 요청, mobileAuthenticationToken AuthRequest) {authRequest.SetDetails (authenticationDetailsSource.BuildDetails (요청)); } public void setpostonly (부울 postonly) {this.postonly = postonly; } public String getMobileparameter () {return mobileparameter; } public void setmobileparameter (String mobileparameter) {this.mobileparameter = mobileparameter; } public boolean ispostonly () {return postonly; }}생산 토큰 위치
/** * @Author 길이 * @Date 2018/1/8 * 휴대폰 번호 로그인이 성공적이며 Oauth Token */ @ComponentPublic Class MobilEloginsUccessHandler를 구현합니다. @autowired 개인 ObjectMapper ObjectMapper; @autowired private clientDetailsService ClientDetailSService; @autowired private congridationerizeRvertOkenservices AuthorizationServertOkenServices; @override public void onauthenticationSuccess (httpservletrequest request, httpservletreponse 응답, 인증 인증) {string header = request.getheader ( "Authorization"); if (header == null ||! header.startSwith ( "BASIC"))) {새 새로운 UNAPPORVEDCLIENTEATHETICATIONEXCEPTION ( "요청 헤더의 클라이언트 정보가 비어 있습니다"); } try {string [] tokens = extractanddecodeheader (헤더); Tokens.length == 2; 문자열 clientId = 토큰 [0]; 문자열 clientsecret = 토큰 [1]; jsonobject params = new JsonObject (); params.put ( "clientId", clientId); params.put ( "ClientSecret", ClientsEcret); params.put ( "인증", 인증); ClientDetails ClientDetails = ClientDetailsService.loadClientByClientId (ClientId); TokenRequest TokenRequest = new TokenRequest (maputil.newhashmap (), clientId, clientDetails.getScope (), "mobile"); Oauth2request Oauth2request = tokenrequest.createoauth2request (clientDetails); oauth2authentication oauth2authentication = 새로운 oauth2authentication (oauth2request, 인증); Oauth2accesstoken OAuth2accesstoken = AwricizationServertOkenServices.CreateAccessToken (OAUTH2Authentication); logger.info ( "토큰 성공을 얻습니다 : {}", oauth2accesstoken.getValue ()); 응답 .SetchAracterEncoding (CommonConstant.utf8); Response.SetContentType (CommonConstant.content_type); printwriter printwriter = response.getwriter (); printwriter.append (ObjectMapper.writeValueAsString (oauth2accesstoken)); } catch (ioexception e) {새로운 badcredentialsexception 던지기 ( "기본 인증 토큰을 해독하지 못했다"); }} /*** 헤더를 사용자 이름과 비밀번호로 디코딩합니다. * * @throws 기본 헤더가 존재하지 않거나 유효하지 않은 경우 * @throws badcredentialsexception * base64 */ private string [] extractanddecodeheader (string header)는 ioexception {base [] base64token = header.substring (6) .getBytes ( "utf-8"); 바이트 [] 디코딩; try {decoded = base64.decode (base64token); } catch (delegalargumentexception e) {새로운 badcredentialsexception 던지기 ( "기본 인증 토큰을 해독하지 못했다"); } string token = 새 문자열 (decoded, commonConstant.utf8); int delim = token.indexof ( ":"); if (delim == -1) {New BadcredentialSexception ( "Invalid Basic Authentication Token"); } 새 문자열을 반환합니다 [] {token.substring (0, delim), token.substring (delim + 1)}; }}위의 사용자 정의를 구성하십시오
// ** * @Author 길이 * @Date 2018/1/9 * 휴대폰 번호 로그인 구성 포털 */ @ComponentPublic Class MobilesEcurityConfigurer 확장 SecurityConfigurerAdapter <defaultsecurityfilterchain, httpsecurity> {@autowired private mobileloginsuccessuccessandler; @autowired private userervice userservice; @override public void configure (httpsecurity http) 예외 {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); }}스프링 보안 구성 위에 지정된 집계 구성
/** * @author length * @date 2018 년 1 월 9 일 14:01:25 * 인증 서버 열기 인터페이스 구성 */ @configuration @enablerEsouresOrceserPublic Class ResourceserVerConfiguration 확장 리소스 러버 ConconfigerAradapter {@autowired private filterlscopertiesconifg filsproperlsconifg; @autowired Private MobilesecurityConfigurer MobilesecurityConfigurer; @override public void configure (httpsecurity http)는 예외 {registry .antmatchers ( "/mobile/token"). harmissionall () .AnyRequest (). authentated () .csrf (). disable (); http.apply (MobilesecurityConfigurer); }}사용
코드 사본은 다음과 같습니다.
CURL -H "승인 : 기본 CGLNONBPZW =="-d "grant_type = mobile & scope = server & mobile = 17034642119 & code ="http : // localhost : 9999/auth/mobile/token
소스 코드
gitee.com/log4j/를 참조하십시오.
Spring Cloud 및 Spring Security OAuth2.0을 기반으로 Enterprise 수준 인증 및 인증이 개발되어 공통 서비스 모니터링, 링크 추적, 로그 분석, 캐시 관리, 작업 일정 및 기타 구현을 제공합니다.
전체 로직은 스프링 보안의 usernamepassword 로그인 모드에서 구현되며 소스 코드를 참조 할 수 있습니다.
검증 코드의 발행 및 확인 논리는 비교적 간단합니다. 이 방법 후 글로벌 피터를 사용하여 요청의 코드가 휴대폰 번호와 일치하는지 여부를 결정하십시오. 주요 논리는 토큰의 매개 변수입니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.