검증 코드 로직
또한 프로젝트에서 검증 코드도 수행했습니다. 인터넷에는 검증 코드를 생성하는 많은 코드가 있으며 일부 타사 JAR 패키지도 아름다운 검증 코드를 생성 할 수 있습니다. 검증 코드 로직은 매우 간단합니다. 로그인 페이지에 이미지 태그를 넣고 SRC는 컨트롤러를 가리 킵니다. 이 컨트롤러는 생성 된 이미지를 반환하고 출력 스트림을 페이지로 반환합니다. 이미지를 생성하는 동안 이미지의 텍스트가 세션에 배치됩니다. 로그인 할 때 입력 된 검증 코드를 가져와 세션에서 꺼내십시오. 둘을 비교하십시오. 교사는 Spring Security Integrated Verification Code를 사용하는 것이 내가 말한 것과 동일하지만보다 표준화되고 일반적이라고 말했습니다.
Spring Security는 일련의 필터 체인이므로 여기서 검증 코드는 필터로 선언되어 필터 체인의 로그인 필터 전에 추가 된 다음 예외 클래스를 사용자 정의하여 확인 코드의 오류 메시지에 응답합니다.
코드 구조 :
검증 코드는 핵심 프로젝트에 배치되며 구성은 브라우저 프로젝트에서 수행됩니다.
메인 코드 :
1. ImageCode :
먼저 imageCode 클래스는 확인 코드 이미지, 텍스트 및 만료 시간을 캡슐화합니다.
package com.imooc.security.core.validate.code; import java.awt.image.bufferedimage; import java.time.localdateTime; import java.time.localtime;/*** verification code* classname : imagecode* @description : 검증 코드*/공개 classor yahogan* @date March 1, 2018, @date am march 1, BufferedImage 이미지; 개인 문자열 코드; Private LocalDateTime expiretime; // 만료 시간대/** ** * <p> 설명 : </p> * @param image * @param code * @param expipreetn hets hog it */public imagecode (bufferedImage image, String Code, int expiretn) {super (); this.image = 이미지; this.code = 코드; // 만료 시간 = 현재 시간 + 만료 된 초 수 this.expiretime = localDateTime.now (). plusseconds (expiretn); } public imageCode (bufferedImage image, 문자열 코드, localDateTime expiretime) {super (); this.image = 이미지; this.code = 코드; this.expiretime = e. } / *** 검증 코드가 만료되었는지 여부* @description : 검증 코드가 만료되었는지 여부* @param @return true 만료, 거짓이 만료되지 않음* @return boolean true 만료, 거짓이 만료되지 않음* @Throws* @Throws* @Throws* / public boolean isexpreired (recline isexpreirect) {return inexpreirect () } public bufferedImage getImage () {return image; } public void setImage (bufferedImage image) {this.image = image; } public String getCode () {return code; } public void setCode (문자열 코드) {this.code = code; } public localDateTime getExpiretime () {return expiretime; } public void setExpiretime (LocalDateTime expiretime) {this.expiretime = expiretime; }}VerifyCode : 검증 코드를 생성하기위한 도구 클래스. 여기 http://www.cnblogs.com/lihaoyang/p/7131512.html, 물론 타사 항아리 패키지를 사용할 수도 있습니다.
ValideCodeexception : 캡슐화 된 검증 코드 예외
/** * @Title : validAteCodeexception.java * @package com.imooc.security.core.validate.code * @description : todo * @author lihaoyang * @date 2018 */패키지 com.imooc.security.core.validate.code; org.springframework.security.core.authenticationexception;/*** classname : validatecodeexception* @description : 검증 코드 오류 예외, 인증 예외 스프링 보안을 상속하는 인증 예외* @author lihaoyang* @date 2018*/public classe validecodeexception {/** @fieldsoide on on on on onivelds on extrends el 정적 최종 긴 SerialversionUID = 1L; public valideCodeexception (String MSG) {Super (MSG); }}ValideCodeFilter : 검증 코드 필터
LOGIC : OncePerRequestFilter를 상속하면 필터가 매번 한 번만 호출되도록하고 (이유가 확실하지 않음) 인증 실패 프로세서에 주입하고 확인이 실패한 경우 호출됩니다.
package com.imooc.security.core.validate.code; import java.io.ioexception; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpervletrequest; import javax.servlet.htttprest; importfronge; org.apache.commons.lang.stringutils; import org.springframework.security.web.authentication.authenticationfailurehandler; import org.springframework.social.connect.web.httpsessionsessionstrategrate org.springframework.web.bind.servletrequestbindexception; import org.sprameframework.web.bind.servletrequestutils; import org.spramframework.web.context.request.servletwebrequest; import org.springframework.web.filter.filter.filter. 로그인 검증 코드 필터 * classname : validateCodeFilter * @Description : * OnePerRequestFilter : Spring에서 제공하는 도구는 필터가 매번 한 번만 호출되도록 보장합니다 * @Author lihaoyang * @Date 2018 */Public Class validequestFilter {// 공개 Classe validequestfilter {// Authordator Procersity Proceptionfailer INGUDINGIONE AuthenticationFailureHandler; // 세션 도구 클래스 개인 sessionstrategy sessionstrategy = new httpsSessionSessionsTrategy (); @override protected void dofilterinternal (httpservletrequest request, httpservletreponse 응답, Filterchain Filterchain)은 servletexception, ioexception {// 로그인 요청 인 경우 (stringutils.equals ( "/Authentication/form", request.getRequesturi ()를 실행합니다. && stringUtils.equalSeignoreCase (request.getMethod (), "post"))) {try {validate (new servletwebrequest (request)); } catch (validAteCodeexception e) {// 오류 핸들러를 호출하고 최종적으로 자체 authenticationFailureHandler를 호출합니다. 반환; // 메소드를 끝내고, 더 이상 필터 체인을 호출하지 않음}} // 로그인 요청이 아닙니다. 다른 필터 체인 filterchain.dofilter (요청, 응답)를 호출하십시오. } /** * 확인 검증 코드 * @description : 검증 검증 코드 * @param @param request * @param @thlerrows servletrequestbindexception * @return void * @throws validecodeexception * @author lihaoyang * @date 3 월 2 일, 2018 년 /개인 void valuctate {servletwequest returectecte) 세션에서 imageCode 객체를 aideCode imageCodeInsession = (imageCode) sessionstrategy.getAttribute (request, validateCodeController.session_key); // 요청 문자열에서 확인 코드를 꺼냅니다. imageCodeInRequest = servletRequestUtils.getStringParameter (request.getRequest (), "imageCode"); // (stringUtils.isBlank (imageCodeInRequest)) {wash new validAteCodeexception ( "확인 코드가 비어있을 수 없음"); } if (imageCodeInsession == null) {wrach new validAteCodeexception ( "확인 코드가 존재하지 않으면 확인 코드를 새로 고침하십시오"); } if (imageCodeInsession.isexpired ()) {// 세션 sessionstrategy.removeattribute에서 만료 된 검증 코드를 제거합니다 (request, ValideCodeController.session_key); 새로운 valideCodeexception을 던지십시오 ( "확인 코드가 만료되었습니다. 확인 코드를 새로 고치십시오"); } if (! stringUtils.equalSeignoreCase (imageCodeInsession.GetCode (), imageCodeInRequest)) {wrach new validAteCodeexception ( "검증 코드 오류"); } // 확인이 전달되어 세션 sessionstrategy.removeattribute (request, validatecodecontroller.session_key)에서 확인 코드를 제거합니다. } public authenticationFailureHandler getAuthenticationFailureHandler () {return AuthenticationFailureHandler; } public void setAuthenticationFailureHandler (AuthenticationFailureHandler AuthenticationFailureHandler) {this.AuthenticationFailureHandler = AuthenticationFailureHandler; }}ValideCodeController : 검증 코드 제어를 생성합니다
package com.imooc.security.core.validate.code; import java.io.ioexception; import javax.imageio.imageio; import javax.servlet.http.htttp.httpervletrequest; import javax.servlet.htttp.httpservletresponse; import org.springframework.social.connect.web.httpssessionsessionstrategy; import org.springframework.social.connect.web.sessionstrategy; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.bind.annotation org.springframework.web.context.request.servletwebrequest;/** * valiation codecontrol * classname : validatecodecontroller * @description : todo * @author lihaoyang * @date 3 월 1 일, 2018 */ @restcontrollerpublic classe {restcontrollerpublic classe {restcontrollerpublic classe valideconcon controller valideconcon controller "session_key_image_code"; // 세션을 받기 개인 SessionStrategy sessionstrategy = new httpsSessionSessionsTrategy (); @GetMapping ( "/verifyCode/Image") public void createCode (httpservletRequest 요청, httpservletResponse 응답)는 ioexception {imageCode imageCode = createImageCode (요청, 응답); sessionstrategy.setAttribute (새로운 servletwebrequest (요청), session_key, imagecode); imageio.write (imageCode.getImage (), "jpeg", response.getOutputStream ()); } private imageCode createImageCode (httpservletRequest request, httpservletResponse 응답) {verifyCode QuerifyCode = new verifyCode (); 새 imageCode (verifyCode.GetImage (), verifyCode.GetText (), 60); }}BrowserSecurityConfig 의 필터 구성 :
패키지 com.imooc.security.browser; import org.springframework.bean.bean.bean.bean.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter; import org.springframework.security.crypt.bcrypt.bcryptpasswordwordwordwordwordwordwordwordwordwordwordword org org.springfram.secrity.crypto.prasser org.springframework.security.web.authentication.authenticationfailurehandler; import org.springframework.security.web.authentication.authenticationfailurehandler; import org.springframework.security.web.authentication.usernamepassortestionfilter; com.imooc.security.core.properties.securityProperties; import com.imooc.security.core.validate.code.validatecodefilter; @configuration // import class browsersecurityconfig는 websecurity configerAdapter {// withiforation @aUt websine weblication @aut @aut @af terveration을 확장합니다. SecurityProperties SecurityProperties; // 성공적인 로그인 후 사용자 정의 된 프로세서 @autowired private authenticationsuccesshandler imoocauthenticationsuccesshandler; // 사용자 정의 인증 실패 프로세서 @autowired private authenticationfailureHandler imoocauthenticationFailureHandler; // org.springframework.security.crypto.password.password.passwordoder @bean public public besponsedencoder passwordcoder () {// bcryptpasswordencoder empactionencoder return new bcryptpasswordwordencoder (); } // 버전 2 : 구성 가능한 로그인 페이지 @override protected void configure (httpsecurity http)는 예외 {// validecodeFilter valideCodeFilter validAteCodeFilter = new ValidAcodeFilter (); // 확인 코드 필터에서 validAteCodeFilter.setAuthenticationFailureHandler (imoocauthenticationFailureHandler)에서 자신의 오류 처리를 사용합니다. // 점프 양식 로그인을 점프하기 위해 인증이 필요한 인터페이스를 구현, 보안 = 인증 + 권한 부여 //http.httpbasic () // 이것은 기본 팝업 상자 인증 // http.addfilterbefore (validatecodefilter, usernamepasswordauthenticationfilter.class)의 VEMATECODEFILTER (VALITACODEFILTER) //) // authentication.loginPage ( "/augentication/require") // 프로세스 사용자 인증 브라우저 SecurityController // 필터 로그인 usernamepasswordauthenticationFilter 기본 로그인 URL은 "/login"입니다. .successhandler (imoocauthenticationsuccesshandler) // 사용자 정의 인증 postprocessor.failurehandler (imoocauthenticationfailuderhandler) // 로그인 실패 후 처리. securityProperTies.getBrowser (). getLoginPage () : user-configured login page.antMatchers ( "/augentication/require", infocentication.getBrowser (). getLoginPage (), // 필터를 저장하지만 오류가 아니지만 "/verifycode/image"). request.authenticated () // Identity Authentication이 필요합니다. }}로그인 페이지 : 로그인 페이지는 비교적 대략적으로 이루어집니다. 실제로, 확인 코드 입력이 초점을 잃으면 확인 코드를 확인할 수 있습니다. 클릭 이미지를 사용하여 검증 코드 기능을 새로 고칠 수 있으므로 여기서는하지 않습니다.
<body> 데모 로그인 페이지. <br> <form action = "/authentication/form"method = "post"> <table> <tr> <td> username : </td> <td> input type = "text"name = "username"/> </td> <td> </td> </td> <t> <td> password : </td> <td> <td> </td> </tr> <tr> <td> 검증 코드 : </td> <td> <입력 유형 = "text"name = "imageCode"/> </td> <td> <img src = "/gryifycode/image"/> </td> </tr> <tr> <td colspan = "align =" "" "" "" "". 유형 = "제출"> 로그인 </button> </td> </tr> </table> </form> </body>
http : // localhost : 8080/demo-login.html을 방문하십시오 :
사용자 정의 예외 정보에 응답합니다
일반적인 기능은 문제가되지 않습니다. 그러나 검증 코드 사진의 너비와 높이, 만료 시간, 필터링 된 URL 및 Verification Code Logic과 같이 보편적이지는 않습니다. 이것들은 살아있을 수 있으며 이제 필터에 검증 코드를 만드는 이점이 반영됩니다. 필터링 해야하는 URL을 구성 할 수 있습니다. 때로는 로그인 페이지에 검증 코드가 필요할 수도 있습니다.
1. 일반화 수정을위한 검증 코드의 기본 매개 변수는 일치 할 수 있습니다.
구성 가능하게 만들어졌으며 응용 프로그램은 모듈을 말하고 직접 구성합니다. 구성되지 않은 경우 기본 구성을 사용하십시오. 또한 구성은 요청 URL 또는 응용 프로그램에서 선언 할 수 있습니다. 교사는 실제로 교사이며 코드는 매우 다재다능합니다!
내가 달성하고자하는 효과는 Application.properties에서 그러한 구성을 만드는 것입니다.
#verification 코드 이미지 너비, 높이, 문자 수 imooc.security.mage.width = 100imooc.security.code.image.height = 30imooc.security.code.image.length = 6
그런 다음 확인 코드의 효과를 제어 할 수 있습니다. 확인 코드는 이미지 확인 코드 및 SMS 확인 코드로 나누어 져 있으므로 SpringBoot의 사용자 정의 구성 파일을 사용하고 해당 Java 클래스를 선언 해야하는 레벨 .code.image를 사용할 수 있습니다.
코드 속성은 SecurityProperties에서 선언해야합니다.
package com.imooc.security.core.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Configuration;/** * Custom configuration items* ClassName: SecurityProperties * @Description: Custom configuration items* This class will read all configuration items starting with imooc.security in application.properties * * imooc.security.browser.loginpage = /demo-login.html * 브라우저 구성은 브라우저 프로파트로 읽습니다. * 이것은 포인트로 나뉘어 있으며 레벨과 레벨은 클래스의 속성에 해당합니다. 2018*/@configurationProperties (prefix = "imooc.security") 공개 클래스 SecurityProperties {private browserProperties browser = new BrowserProperties (); Private ValideCodeProperties Code = 새로운 ValidAteCodeProperties (); public browserProperties getBrowser () {return browser; } public void setBrowser (BrowserProperties 브라우저) {this.browser = 브라우저; } public valideCodeProperties getCode () {return code; } public void setCode (ValidAteCodeProperties code) {this.code = code; }}ValideCodeProperties :
package com.imooc.security.core.properties;/*** 검증 코드 구성* classname : validatecodeproperties* @description : 검증 코드에는 이미지 확인 코드, SMS 확인 코드 등이 포함되어 있으므로 레이어가 @author lihaoyang* @date 3 월 2, 2018*/public validecropies가 포함되어 있습니다. 구성 개인 imagecodeproperties image = 새로운 imagecodeproperties (); public imagecodeproperties getImage () {return image; } public void setImage (imageCodeProperties image) {this.image = image; }}imagecodeproperties :
패키지 com.imooc.security.core.properties;/*** 이미지 확인 코드 구성 클래스* className : imageCodeProperties* @Description : 이미지 확인 코드 구성 클래스* @Author lihaoyang* @Date 2018*/public arplatery imageCodeProperties {// picture width width = 67; // 사진 높이 개인 int 높이 = 23; // 검증 코드 수 문자 개인 int 길이 = 4; // 만료 시간 private int expireIn = 60; public int getWidth () {리턴 너비; } public void setwidth (int width) {this.width = 너비; } public int getheight () {리턴 높이; } public void setheight (int 높이) {this.height = 높이; } public int getLength () {리턴 길이; } public void setLength (int length) {this.length = 길이; } public int getExpirein () {return expirein; } public void setexpirein (int expirein) {this.expirein = expirein; }}요청 수준 구성의 경우 요청에 확인 코드 매개 변수가 포함 된 경우 요청을 사용하십시오.
ValideCodeController의 CreateImageCode 메소드는 요청 매개 변수에 이러한 매개 변수가 있는지 여부를 결정하기 위해이를 제어하는 데 사용됩니다. 그렇다면, Verification Code Generation Class VerifyCode로 전달되며, 이는 생성 중에 동적으로 제어 될 수 있습니다.
Private ImageCode CreateImageCode (httpservletRequest 요청, httpservletResponse 응답) {// 먼저 요청에서 문자의 길이, 너비 및 숫자 매개 변수를 읽습니다. int height = servletrequestutils.getIntParameter (요청, "높이", securityProperties.getCode (). getImage (). getheight ()); int charlength = this.securityProperties.getCode (). getImage (). getLength (); verifyCode verifyCode = 새 verifyCode (너비, 높이, charlength); 새 imageCode (verifyCode.GetImage (), verifyCode.GetText (), this.SecurityProperTies.getCode (). getImage (). getExpirein ()); }verifycode :
public verifycode (int w, int h, int charlength) {super (); this.w = w; this.h = h; this.charlength = charlength; }실험 : 데모 프로젝트에서 응용 프로그램 수준 구성을 수행합니다
양식에 로그인하여 요청 수준 구성을 만듭니다
<img src = "/verifycode/image? 너비 = 200"/>
입장:
길이는 요청 단계 대역의 매개 변수 200이고 높이는 30이고 문자는 6입니다.
2. 검증 코드 인터페이스 보편적 수정의 인터페이스를 구성 할 수 있습니다.
첫 번째 효과는 application.properties 에서 인터셉트 해야하는 인터페이스를 동적으로 구성하는 것입니다.
ImageCodeProperties 새로운 속성을 추가했습니다 : private String url ; // 인터셉트 된 URL은 위의 이미지의 구성과 일치하는 것입니다.
코어, 검증 코드 필터를 수정해야합니다.
1. 인터셉터에서 세트를 설정하여 인터셉트 해야하는 구성 파일에 구성된 URL을 저장합니다.
2. 초기화 비 인터페이스를 구현하십시오. 목적 : 다른 모든 매개 변수가 조립되면 가로 채워야하는 URL의 값을 초기화하고 AfterProperTiesset 메소드를 다시 작성하여 구현하십시오.
3. SecurityProperties를 주입하고 구성 파일을 읽으십시오
4. ANTPATHMATCHER 도구 클래스를 인스턴스화합니다.
5. 브라우저 프로젝트에서 BrowserSecurityConfig를 설정하여 AfterProperTiesset 메소드를 호출하십시오.
6. 응용 프로그램에서 필터링 할 URL을 구성합니다. 모듈을 참조하는 데모 프로젝트의 특징.
ValideCodeFilter :
/** * 로그인 검증 코드 필터 * className : validAteCodeFilter * @Description : * 한 번에 제공하는 도구를 상속 받기 위해 Spring : Filter가 매번 한 번만 호출되도록하기 위해 SPRING을 상속받습니다. * 초기화 인터페이스의 목적을 구현하십시오. 2018*/public class validAteCodeFilter 확장 한 exeperRequestFilter는 초기화를 초기화하는 {// 인증 실패 프로세서 개인 인증 authenticationFailureHandler AuthenticationFailureDler; // 세션 도구 클래스 개인 sessionstrategy sessionstrategy = new httpsSessionSessionsTrategy (); // 인터셉트 개인 세트 <string> urls = new Hashset <> (); // 구성 읽기 개인 SecurityProperties SecurityProperties; // 스프링 도구 클래스 개인 AntpathMatcher AntpathMatcher = New AntpathMatcher (); @override public void afterProperTiesset ()는 servletexception {super.afterProperTiesset (); // 구성된 인터셉트 된 문자열의 URL을 읽습니다 [] configurls = stringUtils.splitByWholeseParatorPreserveallTokens (securityProperties.getCode (). getImage (). getUrl (), "); for (string configurl : configurls) {urls.add (configurl); } // 로그인 요청은 urls.add ( "/Authentication/form")를 가로 채워야합니다. } @override 보호 void dofilterinternal (httpservletrequest request, httpservletResponse 응답, FilterChain FilterChain)은 servleTexception, ioException { / *** 요청 된 URL 및 구성 URL 일치 여부를 결정하는지 여부를 결정하는지 여부를 결정합니다. for (string url : urls) {if (antpathmatcher.match (url, request.getRequesturi ())) {action = true; }} if (action) {try {validate (new servletwebrequest (request)); } catch (validAteCodeexception e) {// 오류 핸들러를 호출하고 최종적으로 자체 authenticationFailureHandler를 호출합니다. 반환; // 메소드를 끝내고, 더 이상 필터 체인을 호출하지 않음}} // 로그인 요청이 아닙니다. 다른 필터 체인 filterchain.dofilter (요청, 응답)를 호출하십시오. } // 관련없는 코드 생략 ,,}BrowsersecurityConfig :
URL 구성 :
#verification code 인터셉트 인터페이스 구성 imooc.security.code.image.url =/user,/user/*
테스트 : /사용자 /사용자 /1을 가로 채 렸습니다
확인 코드를 작성하지 않고 로그인 페이지를 방문하십시오.
기대와 일치합니다. 이 시점에서 인터셉트 인터페이스의 동적 구성이 완료됩니다.
3. 확인 코드 생성 로직을 구성 할 수 있습니다
더 잘 작성된 프로그램에는 일반적으로 열린 인터페이스가있어 사용자가 구현을 사용자 정의 할 수 있습니다. 구현하지 않으면 기본 구현을 사용하십시오. 검증 코드 생성을 스스로 구현할 수 있도록이를 수행합시다. 확인 코드 생성 로직을 구성 가능하게하려면 이미지 확인 코드 생성기 클래스를 작성할 수 없습니다. 검증 코드 생성을 validaTeCodeGenerator로 추출해야합니다. ValidAteCodeGenerator, 검증 코드 generator ()를 생성하는 메소드. 확인 코드에는 이미지 확인 코드, SMS 확인 코드 등이 있으므로 이미지 확인 코드 구현 imageCodeGenerator와 같은 검증 모듈에서 기본 구현을 만듭니다. imageCodeGenerator에서는이 클래스에 @Component 주석을 추가하지 않습니다. 그런 다음 검증 코드 Bean을 작성하는 구성 클래스 ValideCodeBeanConfig를 사용하십시오. 이 구성 클래스는 이미지 확인 코드 구현 ImageCodeGenerator, SMS Verification Code 등과 같은 다양한 필수 검증 코드 구현 Bean을 구성합니다. 리턴 유형은 모두 ValidAcodeGenerator입니다. @ConditionalOnMissingBean (이름 = "imageCodeGenerator") 주석을 사용하십시오. 현재 스프링 컨테이너에 ImageCodeGenerator라는 Bean이있는 경우, ImageCodeGenerator라는 Bean이 사용되면, 구성이 없으면 다른 모듈을 참조하는 경우 다른 사람들이 ValidAcodeGenerator 인터페이스를 생성하기 위해 검증 코드를 구현하면 구현 클래스의 이름을 imageCodeGenerator를 사용하여 구현을 사용하여 프로그램이 확장 될 수 있다고 판단 할 수 있습니다.
메인 코드 :
코드 생성기 인터페이스 ValideCodeGenerator :
package com.imooc.security.core.validate.code; import org.springframework.web.context.request.servletwebrequest;/*** verification code interface* classname : validatecodegenerator* @description : todo* @author lihaoyang* @date trming 2, 2018*/public interface interface request. * 이미지 확인 코드 생성 인터페이스 * @Description : todo * @param @param request * @param @return * @return imageCode * @throws * @Author lihaoyang * @Date 2018 년 3 월 2 일 */ imageCode Generator (ServletWebRequest 요청);}
이미지 검증 코드 생성기는 ImageCodeGenerator를 구현합니다.
package com.imooc.security.core.validate.code; import org.springframework.bean.beans.annotation.autowired; import org.springframework.stereotyp.component; import org.springframework.web.bind.servletrequestutils; 가져 오기 org.springframework.web.context.request.servletwebrequest; import com.imooc.security.core.properties.securityProperties;/** * 이미지 확인 코드 생성 클래스 * 클래스 이름 : imageCodeGenerator * @Description : @Author Lihaoyang * @Date Army */ProbliceGeNerator 2, imageCodeGater ValidAcodeGenerator {@autowired private securityProperties SecurityProperties; @override public imagecode generator (servletwebrequest request) {// 길이, 너비 및 문자 매개 변수가 있는지 요청에서 먼저 읽습니다. 존재하는 경우, 사용하고 기본 int width = servletrequestutils.getIntParameter (request.getRequest (), "width", securityProperties.getCode (). getImage (). getWidth ()); int height = servletrequestutils.getIntParameter (request.getRequest (), "height", securityProperties.getCode (). getImage (). getheight ()); int charlength = this.securityProperties.getCode (). getImage (). getLength (); verifyCode verifyCode = 새 verifyCode (너비, 높이, charlength); 새 imageCode (verifyCode.GetImage (), verifyCode.GetText (), this.SecurityProperTies.getCode (). getImage (). getExpirein ()); } public SecurityProperties getSecurityProperties () {return SecurityProperties; } public void setsecurityProperties (SecurityProperties SecurityProperties) {this.securityProperties = SecurityProperties; }}ValideCodeBeanConfig :
패키지 com.imooc.security.core.validate.code; import org.springframework.bean.beans.annotation.autowired; import org.springframework.boot.autoconfigure.condition.condition.condition.condition.condition.condition.onmissingbean; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import com.imooc.security.core.properties.securityproperties;/** * validecodegenerator의 실제 구현 클래스의 Bean을 구성하십시오 * @dationname : validatecodecodecoderconfig adecode * @validatecodegenerator의 bean을 구성합니다. 이미지 확인 코드의 구현 및 SMS Verification Code의 구현과 같은 ValidAteCodeGenerator *의 실제 구현 클래스의 Bean을 조정하십시오. * @Author lihaoyang * @Date 2018 년 3 월 5 일 */ @configurationPublic Class validAcodeBeanConfig {@autowive private securityProperties SecurityProperties; /** * @description : * @ConditionalOnMissingBean 주석은 스프링 컨테이너에 ImageCodeGenerator가 없을 때 기능이 프로그램을보다 확장 가능하게 만드는 것임을 의미합니다. 구성 클래스는 코어 모듈에서 구성됩니다. 즉, 모듈 *을 지칭하는 프로젝트에 자체 구현이있는 경우 ValidAteCodeGenerator 인터페이스를 구현하고 자체 구현을 정의합니다. 이름을 imageCodeGenerator라고도합니다. * *는 애플리케이션 수준 구현을 구현하는 데 사용되며 그러한 구현이없는 경우이 기본 구현을 사용하십시오. * @param @return * @return validAteCodeGenerator * @Throws * @Author lihaoyang * @Date 2018 년 3 월 5 일 */ @Bean @Bean @ConditionalOnMissingBean ( "imageCodeGenerator") public valideCodeGenerator ImageCodeGenerator () {imageCodeGenerater CodeGenerator = 새로운 imageCodeGenerator (); CodeGenerator.SetSecurityProperties (SecurityProperties); 반환 코드 게이터; }}이러한 방식으로 모듈 이이 확인 코드 모듈을 지칭하면 다음과 같은 구현을 사용자 정의합니다.
package com.imooc.code; import org.springframework.stereotyp.component; import org.springframework.web.context.request.servletwebrequest; import com.imooc.security.core.validate.code.imagecode; 가져 오기 com.imooc.security.core.validate.code.validatecodegenerator; @component ( "imageCodeGenerator") public class demoimagecodegenerator empailateCodeGenerator {@override public imageCode Generator (ServletWebRequest 요청) {System.err.err.err.err.err.er.err.err.err.err.println, "); 널 리턴; }}이러한 방식으로 ValideCodebeanConfig가 확인 코드 Bean을 구성하면 사용자의 사용자 정의 구현을 사용합니다.
전체 코드는 github : https://github.com/lhy1234/spring-security에 배치됩니다
요약
위는 편집기가 소개 한 스프링 보안 이미지 확인 코드 기능의 예제 코드입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!