Spring Security-- 验证码功能的实现

简介

在spring security的内置login处理是无法满足要求的,需要自己进行各种定制。这里介绍login中实现验证码的实现。

实现方法

可以有三种方法可以实现验证码的功能

第一种

自定义一个filter,放在SpringSecurity过滤器之前,在用户登录的时候会先经过这个filter,然后在这个filter中实现对验证码进行验证的功能,这种方法不推荐,因为它已经脱离了SpringSecurity

第二种

自定义一个filter让它继承自UsernamePasswordAuthenticationFilter,然后重写attemptAuthentication方法在这个方法中实现验证码的功能,如果验证码错误就抛出一个继承自AuthenticationException的验证吗错误的异常比如(CaptchaException),然后这个异常就会被SpringSecurity捕获到并将异常信息返回到前台,这种实现起来比较简单。

@Override  
public Authentication attemptAuthentication(HttpServletRequest request,  
        HttpServletResponse response) throws AuthenticationException {  

    String requestCaptcha = request.getParameter(this.getCaptchaFieldName());  
    String genCaptcha = (String)request.getSession().getAttribute("code");  

    logger.info("开始校验验证码,生成的验证码为:"+genCaptcha+" ,输入的验证码为:"+requestCaptcha);  

    if( !genCaptcha.equals(requestCaptcha)){  
        throw new CaptchaException(  
                this.messageSource.getMessage("AbstractUserDetailsAuthenticationProvider.badCaptcha",null,"Default",null));  
    }  
    return super.attemptAuthentication(request, response);  
}  

接着在配置文件中配置:

<bean id="loginFilter" class="com.zrhis.system.security.DefaultUsernamePasswordAuthenticationFilter">  
    <property name="authenticationManager"  ref="authenticationManager"></property>  
    <property name="authenticationSuccessHandler">  
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">  
            <property name="defaultTargetUrl" value="/index.jsp"></property>  
        </bean>  
    </property>  
    <property name="authenticationFailureHandler">  
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
            <property name="defaultFailureUrl" value="/login.jsp"></property>  
        </bean>  
    </property>  
</bean>  

最后在http中加入custom-filter配置,将这个filter放在SpringSecurity的FORM_LOGIN_FILTER之前.

<custom-filter ref="loginFilter" before="FORM_LOGIN_FILTER"/>  

第三种

直接替换掉SpringSecurity的UsernamePasswordAuthenticationFilter,这种比较复杂,但是更为合理,也是我现在正在用的。
如果用这种方法那么http 中的auto-config就必须去掉,而form-login配置也必须去掉,因为这个不需要了,里面的属性都需要我们自行注入。

首先需要创建并配置一个login.jsp作为登录页面EntryPoint

<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">  
    <property name="loginFormUrl" value="/login.jsp" />  
</bean>  

然后在http中配置下

<sec:http access-decision-manager-ref="accessDecisionManager"  
        entry-point-ref="authenticationEntryPoint">  

然后我们来写CaptchaAuthenticationFilter,同样需要继承自UsernamePasswordAuthenticationFilter

public class CaptchaAuthenticationFilter extends UsernamePasswordAuthenticationFilter{  

    public static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "j_captcha";  
    public static final String SESSION_GENERATED_CAPTCHA_KEY = Constant.SESSION_GENERATED_CAPTCHA_KEY;  

    private String captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY;  

    public Authentication attemptAuthentication(HttpServletRequest request,  
            HttpServletResponse response) throws AuthenticationException {  

        String genCode = this.obtainGeneratedCaptcha(request);  
        String inputCode = this.obtainCaptcha(request);  
        if(genCode == null)  
            throw new CaptchaException(this.messages.getMessage("LoginAuthentication.captchaInvalid"));  
        if(!genCode.equalsIgnoreCase(inputCode)){  
            throw new CaptchaException(this.messages.getMessage("LoginAuthentication.captchaNotEquals"));  
        }  

        return super.attemptAuthentication(request, response);  
    }  

    protected String obtainCaptcha(HttpServletRequest request){  
        return request.getParameter(this.captchaParameter);  
    }  

    protected String obtainGeneratedCaptcha (HttpServletRequest request){  
        return (String)request.getSession().getAttribute(SESSION_GENERATED_CAPTCHA_KEY);  
    }  

}  

在配置文件中配置CaptchaAuthenticationFilter

<bean id="captchaAuthenticaionFilter" class="com.zrhis.system.security.CaptchaAuthenticationFilter">  
    <property name="authenticationManager" ref="authenticationManager" />  
    <property name="authenticationFailureHandler" ref="authenticationFailureHandler" />  
    <property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" />  
    <property name="filterProcessesUrl" value="/login.do" />  
</bean>  

<bean id="authenticationSuccessHandler" class="com.zrhis.system.security.SimpleLoginSuccessHandler">  
    <property name="defaultTargetUrl" value="/WEB-INF/app.jsp"></property>  
    <property name="forwardToDestination" value="true"></property>  
</bean>  
<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
    <property name="defaultFailureUrl" value="/login.jsp" />  
</bean>  

从配置文件中就可以看出来authenticationManager、authenticationFailureHandler、authenticationSuccessHandler、filterProcessesUrl等都需要我们自行注入了。
filterProcessesUrl定义的是登录验证的地址,默认的是j_spring_security_check这里我们改成login.do

authenticationSuccessHandler中的defaultTargetUrl定义的是登录成功后跳转到的页面

authenticationFailureHandler中的defaultTargetUrl定义的是登录失败后跳转到的页面

我们的首页app.jsp在/WEB-INF下所以需要使用服务器跳转,所以需要将forwardToDestination设为true,因为客户端跳转是不能直接访问WEB-INF下的内容的。

最后在http中将FORM_LOGIN_FILTER替换掉,最终http中完整的配置就变成了下面的内容

<sec:http access-decision-manager-ref="accessDecisionManager"  
    entry-point-ref="authenticationEntryPoint">  

    <sec:access-denied-handler ref="accessDeniedHandler"/>  

    <sec:session-management invalid-session-url="/login.jsp" />  

    <sec:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>  
    <sec:custom-filter ref="captchaAuthenticaionFilter" position="FORM_LOGIN_FILTER"/>  
</sec:http>  

custom-filter中before是在这个filter之前,after是之后,position是替换。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现自定义短信验证码登录,可以按照以下步骤进行: 1. 添加依赖 在项目中添加 Spring SecuritySpring Security SMS 模块的依赖。 ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>com.github.lanceshohara</groupId> <artifactId>spring-security-sms</artifactId> <version>1.0.2</version> </dependency> ``` 2. 配置 Spring SecuritySpring Security 配置文件中添加配置,包括短信验证码登录相关的配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login/sms").permitAll() .anyRequest().authenticated() .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login/form") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 其中,`SmsCodeAuthenticationSecurityConfig` 是短信验证码登录的相关配置类,需要单独实现。 3. 实现短信验证码登录相关配置 实现 `SmsCodeAuthenticationSecurityConfig` 配置类,其中包括一个短信验证码过滤器和一个短信验证码认证提供者。 ``` @Configuration public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSuccessHandler smsCodeAuthenticationSuccessHandler; @Autowired private SmsCodeAuthenticationFailureHandler smsCodeAuthenticationFailureHandler; @Override public void configure(HttpSecurity http) throws Exception { SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(smsCodeAuthenticationSuccessHandler); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(smsCodeAuthenticationFailureHandler); SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService); http.authenticationProvider(smsCodeAuthenticationProvider) .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 其中,`SmsCodeAuthenticationFilter` 是短信验证码过滤器,需要单独实现。`SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 分别是短信验证码认证成功和失败的处理器,也需要单独实现。 4. 实现短信验证码过滤器 实现 `SmsCodeAuthenticationFilter` 过滤器,重写 `attemptAuthentication` 方法,来处理短信验证码认证请求。 ``` public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; public static final String SPRING_SECURITY_FORM_CODE_KEY = "code"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY; private boolean postOnly = true; public SmsCodeAuthenticationFilter() { super(new AntPathRequestMatcher("/login/sms", "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String mobile = obtainMobile(request); String code = obtainCode(request); if (mobile == null) { mobile = ""; } if (code == null) { code = ""; } mobile = mobile.trim(); SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile, code); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(codeParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public void setCodeParameter(String codeParameter) { this.codeParameter = codeParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; } public final String getCodeParameter() { return codeParameter; } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 5. 实现短信验证码认证提供者 实现 `SmsCodeAuthenticationProvider` 提供者,重写 `authenticate` 方法,来进行短信验证码认证。 ``` public class SmsCodeAuthenticationProvider implements AuthenticationProvider { private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; UserDetails userDetails = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } public UserDetailsService getUserDetailsService() { return userDetailsService; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } } ``` 6. 实现短信验证码认证成功和失败的处理器 实现 `SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 处理器,来处理短信验证码认证成功和失败的情况。 ``` public class SmsCodeAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { super.onAuthenticationSuccess(request, response, authentication); } } ``` ``` public class SmsCodeAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { super.onAuthenticationFailure(request, response, exception); } } ``` 7. 编写控制器 编写控制器,处理短信验证码登录的请求。 ``` @Controller public class LoginController { private final static String SMS_LOGIN_PAGE = "sms-login"; @RequestMapping("/login/sms") public String smsLogin() { return SMS_LOGIN_PAGE; } @RequestMapping(value = "/login/sms", method = RequestMethod.POST) public void smsLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String mobile = request.getParameter("mobile"); String code = request.getParameter("code"); SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(mobile, code); AuthenticationManager authenticationManager = new ProviderManager(Collections.singletonList(new SmsCodeAuthenticationProvider())); Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); request.getRequestDispatcher("/").forward(request, response); } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 以上就是实现自定义短信验证码登录的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值