스프링 보안 사용 분류 :
바이두에 살았던 모든 사람들은 스프링 보안을 사용하는 방법을 알고 있다고 생각합니다. 단순에서 깊이까지 4 가지 사용량이 있습니다.
1. 데이터베이스가 사용되지 않으며 모든 데이터는 구성 파일로 작성되며 공식 문서의 데모이기도합니다.
2. 데이터베이스를 사용하고 스프링 보안에 따라 데이터베이스의 기본 코드 디자인을 구현합니다. 즉, 데이터베이스가 수정 되었고이 방법은 융통성이 없으며 데이터베이스는 매우 간단하고 실용성이 좋지 않음을 의미합니다.
3. 스프링 보안은 Acegi와 다릅니다. 더 이상 기본 필터를 수정할 수는 없지만 필터 삽입을 지원하므로 유연하게 사용하기 위해 자체 필터를 삽입 할 수 있습니다.
4. 폭력적인 수단은 소스 코드를 수정하는 수단입니다. 위에서 언급 한 기본 필터의 수정은 필터를 교체하기 위해 구성 파일을 수정하는 것입니다. 이것은 내부의 소스 코드를 직접 변경하지만 OO 설계 원칙을 준수하지 않으며 실용적이고 사용할 수 없습니다.
이 기사는 주로 Spring Security Custom Authentication Login에 대한 관련 컨텐츠를 소개합니다. 참조와 학습을 위해 공유됩니다. 나는 아래에서 많이 말하지 않을 것입니다. 자세한 소개를 함께 살펴 보겠습니다.
1. 요약
1.1. 소개
Spring Security는 Spring AOP 및 Servlet 필터를 기반으로하는 보안 프레임 워크입니다. 권한 인증 등을 관리합니다.
1.2. 스프링 보안 사용자 정의 인증 프로세스
1) 인증 프로세스
인증되지 않은 인증을 생성합니다
↑ (정보 가져 오기) (AuthenticationToken에 따라 제공자 할당) AuthenticationFilter-> AuthenticationManager-> AuthenticationProvider ↓ (인증) userDetails (일반 쿼리 데이터베이스 획득) ↓ (PASS) AUTHENTICTIONTOKNE는 성공적으로 인증 된 AUTHENTICTIONTOKEN을 생성합니다.
2) 보안 필터 체인 (자원 서버에서 구성)에 AuthenticationFilter를 다음과 같이 추가하십시오.
http.addfilterbefore (AuthenticationFilter, AbstractPreauthenticatedProcessingFilter.class)
또는:
http.addfilterafter (authenticationfilter, usernamepasswordauthenticationfilter.class)
2. SMS 로그인을 예로 들어 보겠습니다
2.1. 개발 환경
2.2. 핵심 코드 분석
2.2.1. 사용자 정의 로그인 인증 프로세스
2.2.1.1. 사용자 정의 인증 로그인 토큰
/** * 모바일 로그인 토큰 * * @Author : CatalPaflat */public class mobileloginauthenticationToken 확장 {private static final long serialversionuid = springsecuritycoreversion.serial_version_uid; 개인 정적 최종 로거 로거 = loggerFactory.getLogger (MobilEloginauthenticationToken.class.getName ()); 개인 최종 대상 교장; public mobileloginauthenticationToken (String Mobile) {super (null); this.principal = 모바일; this.setAuthenticated (false); logger.info ( "MobileloginauthenticationToken setAuthenticated-> False Loading ..."); } public mobileloginauthenticationToken (Object Principal, Collection <? extends wranteDauthority> 당국) {Super (당국); this.principal = 교장; // super.setAuthenticated (true)를 무시할 때 Super를 사용해야합니다. logger.info ( "MobileloginauthenticationToken setAuthenticated-> True Loading ..."); } @override public void setAuthentical (부울 인증) {if (인증) {새로운 불법 불법 행위 렉싱 ( "이 토큰을 신뢰할 수있는 것으로 설정할 수 없습니다 - 대신 부여 된 목록을 사용하는 생성자"); } super.setAuthenticated (false); } @override public object getCredentials () {return null; } @override public object getPrincipal () {return this.principal; } @override public void EraseCredentials () {super.erasecredentials (); }} 메모:
setAuthenticated () : 인증되었는지 여부를 결정합니다
2.2.1.1. 사용자 정의 인증 로그인 필터
/** * 모바일 SMS 로그인 필터 * * @Author : CatalPaflat */public class mobileloginauthenticationFilter 확장 추상화 프로세싱 필터 {private boolean postonly = true; 개인 정적 최종 로거 로거 = loggerFactory.getLogger (MobilEloginaUthenticationFilter.class.getName ()); @getter @setter private String mobileparametername; public mobileloginayuthenticationfilter (String mobileloginurl, String mobileparametername, String httpmethod) {Super (new AntpathrequestMatcher (Mobileloginurl, httpmethod)); this.mobileparametername = mobileparametername; logger.info ( "MobileloginauthenticationFilter Loading ..."); } @override public Authentication rituthentication (httpservletrequest 요청, httpservletresponse 응답)은 AuthenticationException, ioexception, servletexception {if (postonly &&! request.getmethod (). + request.getMethod ()); } // 모바일 문자열 가져 오기 모바일 = acemobile (요청); // 토큰 조립 MOBILELOGINAYTICATIONTOKONTOKEN AUTHREQUEST = NEW MOBILELOGINAYUDETICATIONTOKN (Mobile); // 서브 클래스가 "세부 사항"속성 SetDetails를 설정하도록 허용합니다 (요청, AuthRequest); reture this.getAuthenticationManager (). 인증 (AuthRequest); } / *** ID 인증을 설정하기위한 세부 사항* / private void setDetails (httpservletRequest 요청, mobileloginauthenticationToken AuthRequest) {AuthRequest.SetDetails (AuthentIcicationDetailsSource.BuildDetails (요청)); } / *** 휴대 전화 번호 가져 오기* / 개인 문자열 acemobile (httpservletrequest request) {return request.getParameter (mobileparametername); } public void setpostonly (부울 postonly) {this.postonly = postonly; }}참고 : riteAuthentication () 메소드 :
2.2.1.1. 사용자 정의 인증 로그인 제공자
/** * 모바일 SMS 로그인 인증 제공자 * * @Author : CatalPaflat */public class mobileloginauthenticationProvider는 AuthenticationProvider {private static final logger = loggerfactory.getLogger (mobileloginauthenticationProvider.class.getName ()); @getter @setter private userDetailsService customUserDetailsService; public mobileloginauthenticationprovider () {logger.info ( "mobileloginauthenticationprovider loading ..."); } /*** 인증* /@override public Authentication Authentication (인증 인증)은 AuthenticationException {// 필터 mobileloginauthenticationTokenTokenToken = (MobilELoginaUthenticationToken) 인증에 의해 캡슐화 된 토큰 정보를 가져옵니다. // 사용자 정보 가져 오기 (데이터베이스 인증) userDetails userDetails = CustomUserDetailsService.loadUerByUserName ((String) authenticationToken.getPrincipal ()); // (userDetails == null) {throw new internalAuthenticationServiceException ( "사용자 정보를 얻을 수 없음"); } // mobileloginauthenticationtoken authenticationResult = 새로운 mobileloginauthenticationToken (userDetails, userDetails.getAuthorities ()); AuthenticaticResult.setDetails (AuthenticaticToken.getDetails ()); AuthenticationResult 리턴; } / ** * 토큰 유형에 따라 * / @override public boolean supports (class <?> 인증) {return mobileloginauthenticationtoken.class.isassignablefrom (인증); }}참고 : authenticate () 메소드
2.2.1.1. 사용자 정의 인증 로그인 인증 구성
@Configuration (SpringBeannameConstant.default_custom_custom_mobile_login_authentication_security_config_bn) public class mobileloginauthenticationsecurityConfig는 SecurityConfigerAradapter를 확장합니다. loggerFactory.getLogger (MobilELOGINAYUDENTICITATIONCURITIONFIG.CLASS.GETNAME ()); @Value ( "$ {login.mobile.url}") private String defaultMobilEloginUrl; @Value ( "$ {login.mobile.parameter}") private String defaultMobilEloginParameter; @Value ( "$ {login.mobile.httpMethod}") 개인 문자열 defaultMobilEloginHttpMethod; @autowired private customymlconfig customyMlConfig; @autowired private userDetailsService customUserDetailsService; @autowired private authenticationsuccesshandler customauthenticationsuccesshandler; @autowired Private AuthenticationFailureHandler CustomAuthenticationFailureHandler; public mobileloginauthenticationsecurityconfig () {logger.info ( "mobileloginauthenticationsecurityconfig loading ..."); } @override public void configure (httpsecurity http) 예외 {mobilepojo mobile = customymlconfig.getLogins (). getMobile (); 문자열 URL = mobile.getUrl (); 문자열 파라미터 = mobile.getParameter (). getMobile (); 문자열 httpmethod = mobile.gethttpmethod (); MobileloginauthenticationFilter MobilELoginauthenticationFilter = 새로운 MobilEloginauthenticationFilter (url)? defaultMobilEloginUrl : URL, StringUtils.isblank (매개 변수)? defaultMobileloginUrl : Parameter, StringUtils.isblank (httpmethod)? defaultMobilELOGINHTTPMETHOD : httpMethod); mobileloginauthenticationFilter.setAuthenticationManager (http.getsharedObject (authenticaticManager.class)); MobileloginauthenticationFilter.SetAuthenticationSuccessHandler (CustomAuthenticationSuccessHandler); mobileloginauthenticationFilter.SetAuthenticationFailureHandler (CustomAuthenticationFailureHandler); Mobileloginauthenticationprovider MobileloginauthenticationProvider = New MobileloginauthenticationProvider (); MobileloginauthenticationProvider.SetCustomUserDetailsService (CustomUserDetailsService); http.authenticationprovider (mobileloginauthenticationprovider) .addfilterafter (mobileloginauthenticationfilter, usernamepasswordauthenticationfilter.class); }}참고 : configure () 메소드입니다
Instantiate AuthenticationFilter 및 AuthenticationProvider
Spring Security에 AuthenticationFilter 및 AuthenticationProvider를 추가하십시오.
2.2.2. Redis를 기반으로 사용자 정의 확인 코드를 확인하십시오
2.2.2.1. Redis를 기반으로하는 사용자 정의 검증 코드 필터
/** * 검증 코드 필터 * * @Author : CatalPaflat */ @Component (SpringBeannameConstant.default_validate_code_filter_bn) 공개 클래스 validAteCodeFilter 확장 한 EPERREQUESTFILTER 초기화 비대 {개인 정적 최종 로거 = loggerFactory.getLogger (ValidAteCodeFilter.class.getName ()); @autowired private customymlconfig customyMlConfig; @autowired private redistemplate <객체, 객체> Redistemplate; / *** 요청 된 URL이 구성된 URL과 일치하는지 여부를 확인하는 도구 클래스*/ private antpathmatcher pathmatcher = new AntpathMatcher (); public validecodefilter () {logger.info ( "validaTecodeFilter로드 ..."); } @override protected void dofilterinternal (httpservletrequest request, httpservletresponse 응답, Filterchain filterchain)은 servletexception, ioexception {string url = customymlconfig.getLogins (). getMobile (). geturl (); if (pathMatcher.match (url, request.getRequesturi ())) {String deviceId = request.getheader ( "deviceId"); if (stringUtils.isblank (deviceId)) {wrach new customexception (httpstatus.not_acceptable.value (), "요청의 헤드에있는 deviceid가 아님"); } String CodeParamName = CustomEmlConfig.getLogins (). getMobile (). getParameter (). getCode (); 문자열 코드 = request.getParameter (CodeParamName); if (stringUtils.isblank (code)) {wrach new customexception (httpstatus.not_acceptable.value (), "요청의 매개 변수의 코드가 아님"); } String key = SystemConstant.Default_Mobile_key_pix + deviceId; smscodepo smscodepo = (smscodepo) redistemplate.opsforvalue (). get (key); if (smscodepo.isexpried ()) {Throw new CustomeXception (httpstatus.bad_request.value (), "확인 코드가 만료되었습니다"); } string smscode = smscodepo.getCode (); if (stringUtils.isblank (smscode)) {wrach new customexception (httpstatus.bad_request.value (), "확인 코드가 존재하지 않는다"); } if (stringUtils.equals (code, smscode)) {redistemplate.delete (키); // filterCain.dofilter (요청, 응답)를 보내십시오. } else {wash new customexception (httpstatus.bad_request.value (), "유효성 검사 코드가 잘못되었습니다"); }} else {// filterchain.dofilter (요청, 응답); }}}참고 : Dofilterinternal ()
사용자 정의 검증 코드 필터 확인
2.2.2.2. 스프링 보안 필터 체인에 사용자 정의 검증 코드 필터 추가
http.addfilterbefore (validatecodefilter, acpractPreauthenticatedProcessingFilter.class)
참고 : 인증 전처리 필터에 추가하기 전에
3. 효과를 테스트하십시오
마지막으로 소스 코드 주소가 첨부되어 있습니다 : https://gitee.com/catalpaflat/springsecurity.git (로컬 다운로드)
요약
위는이 기사의 전체 내용입니다. 이 기사의 내용에 모든 사람의 연구 나 작업에 대한 특정 참조 가치가 있기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다. Wulin.com을 지원 해주셔서 감사합니다.