Spring Security는 큰 모듈 이며이 기사에는 사용자 정의 매개 변수의 인증 만 포함됩니다. 스프링 보안의 기본 확인 매개 변수는 일반적으로 충분하지 않은 사용자 이름과 비밀번호 만 있습니다. 시간이 너무 오래 지나갔 기 때문에 일부는 잊고 일부는 누락 될 수 있습니다. 좋아, 말도 안돼.
스프링 및 스프링 보안 구성은 Javaconfig를 사용하며 버전은 4.2.5 및 4.0.4입니다.
전반적인 아이디어 : EntryPoint를 사용자 정의하고 확인을 위해 AuthenticationToken 및 AuthenticationProvider를 확장하기 위해 사용자 정의 매개 변수를 추가하십시오.
첫 번째 정의 Entrypoint :
import org.springframework.security.core.authenticationexception; import org.springframework.security.web.authentication.loginurlauthenticationentrypoint; import javax.servlet.servletexception; import javax.servlet.httpervletrequest; import; javax.servlet.http.http.httpervletresponse; import java.io.ioexception; public class myauthenticationentrypoint 확장 loginurlauthenticationentrypoint {public myauthenticationentrypoint (string loginformurl) {super (loginformurl); } @override public void remence (httpservletrequest request, httpservletResponse 응답, AuthenticationException auxception)는 ioexception, super.commence (요청, 응답, Authexception)를 던졌습니다. }}다음은 토큰입니다. ValidCode는 확인 코드 매개 변수입니다.
import org.springframework.security.authentication.usernamepasswordauthenticationtoken; public class myusernamepasswordauthenticationtoken은 usernamepasswordauthenticationtoken {private string validcode; public myusernamepasswordauthenticationToken (문자열 원칙, 문자열 자격 증명, 문자열 validcode) {super (Principal, Credentials); this.validCode = ValidCode; } public String getValidCode () {return validCode; } public void setValidCode (String ValidCode) {this.validCode = ValidCode; }}계속 처리 필터,
import com.core.shared.validatecodehandle; import org.springframework.security.core.authentication; import org.springframework.security.core.authenticaticexception; import org.springframework.seb.authentication.abstractentaticsingfocessingfilter; org.springframework.security.web.util.matcher.antpathrequestmatcher; import javax.servlet.servletexception; import javax.servlet.http.htttp.httpervletrequest; import javax.servlet.http.htttp.htttp.httpletresponse; java.io.ioexception; public class myValidCodeProcessingFilter 확장 AbstractAuthenticationProcessingFilter {private String usernameparam = "username"; 개인 문자열 passwordparam = "비밀번호"; 개인 문자열 validCodeParam = "ValidAteCode"; public myValidCodeProcessingFilter () {super (new AntpathRequestMatcher ( "/User/Login", "Post")); } @override public Authentication ritHeuthentication (httpservletRequest 요청, httpservletResponse 응답) authenticationException, ioException, servleTeXception {string username = request.getParameter (usernameparam); 문자열 비밀번호 = request.getParameter (passwordParam); String ValidCode = request.getParameter (ValidCodeParam); 유효한 (ValidCode, request.getSession ()); myusernamepasswordauthenticationtoken token = new myusernamepasswordauthenticationToken (사용자 이름, 암호, ValidCode); reture this.getAuthenticationManager (). 인증 (Token); } public void valid (string validCode, httpsestion session) {if (validCode == null) {throw new validCodeErrorException ( "ValidAteCode가 비어 있습니다!"); } if (! validateCodeHandle.MatchCode (session.getId (), validCode)) {throw new validCodeErroreXception ( "ValidCodeError!"); }}} 로그인 양식에서 매개 변수를 수신하는 데 사용되는 세 매개 변수를 별도로 정의하십시오. 시공 방법은 로그인 URL과 Post Method가 필요한 게시물을 제공합니다.
다음은 인증입니다. 인증 사용자 이름과 암호가 도착하기 전에 확인 코드를 인증했습니다.
다음은 툴 클래스 ValideCodeHandle 및 ValidCodeErroreXception입니다.
import java.util.concurrent.concurrenthashmap; public class validaTecodeHandle {private static concurrenthashMap validAteCode = new ConcurrEthashMap <> (); public static concurrenthashmap getCode () {return validAteCode; } public static void save (string sessionId, String Code) {validAteCode.put (sessionId, code); } public static string getValidAteCode (String SessionId) {Object obj = validAteCode.get (sessionId); if (obj! = null) {return string.valueof (obj); } return null; } public static boolean matchcode (String sessionId, String inputCode) {String savecode = getValidateCode (sessionId); if (savecode.equals (inputCode)) {return true; } false를 반환합니다. }}여기서는 AuthenticationException을 상속하여 보안 인증 실패임을 나타내므로 후속 실패 프로세스가 따를 것입니다.
import org.springframework.security.core.authenticationException; public class validcodeerRorexception authenticationException {public validcodeerRorexception (string msg) {super (msg); } public validcodeerRorexception (String MSG, Throwable T) {Super (MSG, T); }}다음은 제공자입니다.
org.springframework.security.authentication.badcredentialsexception; import org.springframework.security.authentication.usernamepasswordauthenticationtoken; import org.springframework.security.authentication.dao.daouthenticationprovider; import org.springframework.security.core.authenticationexception; import org.springframework.security.core.userdetails.userdetails; public class myauthenticationprovider 확장 {@override public boolean supports (class <?> return) myusernamepasswordauthenticationtoken.class.isassignablefrom (인증); } @override protected void acceserDetails (userDetails userDetails, usernamepasswordauthenticationTokenTokenTokenTokenTokentication) authenticationException {object salt = null; if (getSaltsource ()! = null) {salt = getSaltsource (). getSalt (userDetails); } if (augentication.getCredentials () == null) {logger.debug ( "인증 실패 : 자격 증명이 제공 없음"); 새로운 badcredentialsexception을 던지십시오 ( "사용자 이름 또는 비밀번호 오류!"); } string presentedPassword = augentication.getCredentials (). toString (); if (! this.getPasswordEncoder (). ispasswordValid (userDetails.getPassword (), presentedPassword, salt)) {logger.debug ( "인증 실패 : 비밀번호가 저장된 값과 일치하지 않습니다"); 새로운 badcredentialsexception을 던지십시오 ( "사용자 이름 또는 비밀번호 아래!"); }}} 지원 방법은 사용자 정의 토큰의 사용을 지정하고 추가 조정 체크 메소드는 상위 클래스의 논리와 정확히 동일하며 예외에 의해 반환 된 정보를 변경했습니다.
다음은 성공적인 인증과 실패 인증을 처리하는 핸들러입니다.
import org.springframework.security.core.authentication; import org.springframework.security.web.authentication.simpleurlauthenticationsuccesshandler; import javax.servlet.servletexception; import javax.servlet.httpervletrequest; import; javax.servlet.http.http.httervletresponse; import java.io.ioexception; public class frontauthenticationsuccesshandler 확장 simpleurlauthenticationsuccesshandler {public frontauthenticationsuccesshandler (string defaulttargeturl) {super (defaulttargeturl); } @override public void onauthenticationSuccess (httpservletrequest 요청, httpservletreponse 응답, 인증 인증)는 ioexception, servletexception {super.onauthenticationSuccess (요청, 응답, 인증); }} import org.springframework.security.core.authenticationexception; import org.springframework.security.web.authentication.simpleurlauthenticationfailurehandler; import javax.servlet.servletexception; import javax.servlet.httpervletrequett; Javax.servlet.http.http.httpervletresponse; import java.io.ioexception; public class frontauthenticationfailurehandler는 simpleurlauthenticationfailurehandler {public frontauthenticationfailureHandler (string defaultFailureUrl) {SuperFailureUrl); } @Override public void onauthenticationFailure (httpservletrequest 요청, httpservletreponse 응답, AuthenticationException Exception)는 ioexception, servletexception {super.onauthenticationFailure (요청, 응답, 예외); }}마지막으로 가장 중요한 보안 구성 :
import com.service.user.customerService; import com.web.filter.sitemeshfilter; import com.web.mysecurity.*; import org.spramframework.beans.bean.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.core.annotation.order; import org.springframework.security.authentication.authenticationmanager; import org.spramframework.security.authenticatic.authenticationprovider; org.springframework.security.authentication.providermanager; import org.springframework.security.config.annotation.web.builders.httpsecurity; import org.springframework.security.config.annotation.web.configuration.enablewebsecurity; org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter; import org.springframework.security.crypto.password.password.passwordnencoder; import org.spramework.security.crypto.password.astandardswordword org.springframework.security.web.access.exceptionTranslationFilter; import org.springframework.security.web.authentication.usernamepasswordauthenticationFilter; import org.springframework.security.web.context.abstractsecuritionBapplicationInitiOlozeR; org.springframework.web.filter.characterencodingfilter; import javax.servlet.dispatchertype import javax.servlet.filterregistration; import javax.servlet.servletcontext; import java.util.arraylist; import java.util.enumset; java.util.list;@configuration@enablewebsecuritypublic class securityconfig 확장 actractSecurityWebApplicationInitializer {@bean public parbliceencoder passwordEncoder () {return new StandardPasswordenCoder ( "md5"); } @autowired private customerservice customerservice; @Configuration @Order (1) 공개 정적 클래스 FrontEndWebSecurityConfigUReadapter 확장 WEBSECURITYCONFIGURERADAPTER {@autowired private myValidCodeProcessingFilter myValidCodeProcessingFilter; @override protected void configure (httpsecurity http)는 예외를 {http.csrf (). disable () .authorizerequests () .antmatchers ( "/user/login", "/user/logout"). cermitall () .AnyRequest () .ANYRENTICATION (). .addFilterBefore (MyValidCodeProcessingFilter, usernamepasswordauthenticationFilter.class) .formLogin () .LoginPage ( "/User/Login"). 및 () .Logout () .logoutUrl ( "/user/logout") .LogoutSuccsurl ( "/User/Login"); }}} @Bean (이름 = "FrontAuthenticationProvider") public myauthenticationProvider frontAuthenticationProvider () {myAuthenticationProvider myAuthenticationProvider = new MyAuthenticationProvider (); myAuthenticationProvider.SetUserDetailsService (customerservice); myAuthenticationProvider.setpasswordencoder (passwordencoder ()); myauthenticationprovider를 반환하십시오. } @Bean public authenticationManager authenticationManager () {list <AuthenticationProvider> list = new ArrayList <> (); list.add (FrontAuthenticationProvider ()); AuthenticationManager AuthenticationManager = New ProviderManager (List); Return AuthenticationManager; } @Bean Public MyValidCodeProcessingFilter MyValidCodeProcessingFilter (AuthenticationManager AuthenticationManager) {MyValidCodeProcessingFilter 필터 = New MyValidCodeProcessingFilter (); Filter.SetAuthenticationManager (AuthenticaticAnager); Filter.SetAuthenticationSuccessHandler (FrontAuthenticationSuccessHandler ()); Filter.SetAuthenticationFailureHandler (FrontAuthenticationFailureHandler ()); 반환 필터; } @Bean Public FrontAuthenticationFailureHandler FrontAuthenticationFailureHandler () {새로운 FrontAuthenticationFailureHandler ( "/User/Login"); . } @bean public myauthenticationentrypoint myauthenticationEntrypoint () {새로운 myauthenticationentrypoint ( "/user/login"); }}우선, 그것은 암호화 클래스의 Bean이며 CustomersOrvice는 간단한 쿼리 사용자입니다.
@Service ( "CustomersOrvice") public class customerserviceimpl은 customerservice {@autowired private userdao userdao; @override public userDetails loadUserByUserName (String username)은 usernamenotfoundException {return userDao.FindCustomerByUserName (username); }} 다음은 FrontEndWebSecurityConfigureadapter입니다. 구성 메소드를 다시 작성하고, 먼저 CSRF를 비활성화하고, "/user/login"및 "/user/logout"권한 확인을 멈추고 다른 요청에는 로그인 인증이 필요하고 addfilterbefore ()를 필요로합니다. 보안에서 내 정의 myValidCodeProcessingFilter를 기본 usernamepasswordauthenticationFilter에 추가하기 전에 먼저 사용자 정의 매개 변수 인증을 수행 한 다음 FormLogin ()을 수행하고 로그인 URL 및 로그 아웃 URL을 구성하고 URL 로그인 URL, Login URL 및 Login URL을 로그인합니다.
다음은 AuthenticationProvider, AuthenticationManager, ProcessingFilter, AuthenticationFailureHandler, AuthenticationSuccessHandler 및 EntryPoint의 Bean 표시 선언입니다.
아래는 login.jsp입니다
<body> <div> <form : form autocomplete = "false"commandname = "userdto"method = "post"> <div> <span> <b> $ {spring_security_last_exception.message} </b> </span> </div> username : <form : input path = "username"cssclass = "compontrol : <brcontrol"/>. path = "password"cssclass = "form-control"/>> validaTecode : <form : input path = "validateCode"cssclass = "form-control"/> <label> $ {validate_code} </label> <div> <label> <input type = "check <name" "semp </label"/> me </label> </label> </label " 값 = "제출"/> </form : form> </div> </body>확인 코드가 실패하면 ValidCodeErrorexception이 발생합니다. AuthenticationException이 상속되므로 보안이 AuthenticationException을 만나면 AuthenticationFailureHandler가 트리거됩니다. 위의 Bean은 인증이 실패하고 로그인 URL로 점프한다고 선언하므로 login.jsp에 $ {spring_security_last_exception.message}가 있습니다. 예외 정보는 내가 인증 할 때 발생하여 사용자에게 친숙 할 수 있습니다.
전체 사용자 정의 보안 검증 프로세스가 완료되었습니다
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.