spring security登录校验时检查图片验证码
spring security登录校验时检查图片验证码
抢地主 发表于6个月前
spring security登录校验时检查图片验证码
  • 发表于 6个月前
  • 阅读 36
  • 收藏 0
  • 点赞 0
  • 评论 0

华为云·免费上云实践>>>   

 

spring security登录时校验用户名、密码、图片验证码 3个要素的一个例子。

1、配置登录权限管理及登录过滤。 

spring_security.xml源码:
 

[code]<?xml version="1.0" encoding="UTF-8"?>

<beans:beans
    xmlns="http://www.springframework.org/schema/security" 
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-4.2.xsd         http://www.springframework.org/schema/security         http://www.springframework.org/schema/security/spring-security-4.0.xsd">     <http auto-config="true">
        <!-- 
            若启用跨域请求遗忘机制,<csrf disabled="false" />
            则所有的请求都要加上 csrf令牌,如 login.zul:
            <html:form action="/LMemo/login" method="POST" xmlns:html="native">
                <textbox name="${_csrf.parameterName}" value="${_csrf.token}" />
                ...
            </html:form>
            但是 zk引擎的系统请求(/zkau/**)就会无效。
         -->
        <csrf disabled="true" />
        <!-- zk引擎请求不需要登录 -->
        <intercept-url pattern="/zkau/**" access="permitAll" />
        <!-- 登录、注册页不需要登录 -->
        <intercept-url pattern="/view/login.zul" access="permitAll" />
        <intercept-url pattern="/view/register.zul" access="permitAll" />
        <!-- 需要登录 -->
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
        <!-- 登录过滤 -->
        <custom-filter ref="loginFilter" before="FORM_LOGIN_FILTER" />
        <!-- 登录 -->
        <form-login
            always-use-default-target="true"
            authentication-failure-url="/view/login.zul?login_error=1"
            default-target-url="/view/memo_main.zul"
            login-page="/view/login.zul"
            login-processing-url="/login"
            password-parameter="password"
            username-parameter="username" />
        <!-- 退出 -->
        <logout
            logout-url="/logout"
            logout-success-url="/view/login.zul" />
    </http>       
    <!-- 权限管理 -->
    <authentication-manager id="authenticationManager">
        <authentication-provider user-service-ref="memoUserDetailsServiceImpl">
            <password-encoder hash="plaintext" />
        </authentication-provider>
    </authentication-manager>
     <!-- 全局方法安全 -->
    <global-method-security pre-post-annotations="enabled" />
    <!-- 登录过滤 -->
    <beans:bean id="loginFilter" class="me.linkwork.lmemo.filter.SecuriyLoginFilter">
        <beans:property name="authenticationManager"  ref="authenticationManager"></beans:property>
        <beans:property name="authenticationSuccessHandler">
            <beans:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
                <beans:property name="defaultTargetUrl" value="/view/memo_main.zul"></beans:property>
            </beans:bean>
        </beans:property>
        <beans:property name="authenticationFailureHandler">
            <beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                <beans:property name="defaultFailureUrl" value="/view/login.zul?login_error=1"></beans:property>
            </beans:bean>
        </beans:property>
    </beans:bean>
</beans:beans>



2、登录过滤器中检查图片验证码。 

SecuriyLoginFilter.java源码:
 

[code]package me.linkwork.lmemo.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import me.linkwork.lmemo.constant.MemoCns;
import me.linkwork.lmemo.exception.CaptchaException;
import me.linkwork.lmemo.util.LwToolkit;

/**
 * 登录过滤器
 * @author Linkwork, 276247076@qq.com
 * @since 2016年2月11日
 */
public class SecuriyLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(
            HttpServletRequest request,
            HttpServletResponse response)
                    throws AuthenticationException {
        String inputCode = request.getParameter("code");
        String code = (String) request.getSession().getAttribute(MemoCns.LOGIN_CAPTCHA);
        if(LwToolkit.isBlank(code)
                || (! code.equalsIgnoreCase(inputCode))) {
            throw new CaptchaException("图片验证码不正确!");
        }
        return super.attemptAuthentication(request, response);
    }

}



3、登录用户信息加载处理。 

MemoUserDetailsServiceImpl.java源码:
 

[code]package me.linkwork.lmemo.database.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import me.linkwork.lmemo.database.entity.MemoUserEntity;
import me.linkwork.lmemo.enums.RoleEnum;
import me.linkwork.lmemo.wrap.MemoUserWrap;

/**
 * 登录用户加载处理
 * @author Linkwork, 276247076@qq.com
 * @since 2016年1月30日
 */
@Service
public class MemoUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MemoUserServiceI userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        MemoUserEntity userEntity = this.userService.query(name);
        if (userEntity != null) {
            MemoUserWrap userWrap = new MemoUserWrap(userEntity, RoleEnum.USER.getValue());
            return userWrap;
        }
        throw new UsernameNotFoundException("user name not found!");
    }

}



4、登录用户信息包装。 

MemoUserWrap.java源码:
 

[code]package me.linkwork.lmemo.wrap;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;

import me.linkwork.lmemo.database.entity.MemoUserEntity;

/**
 * 登录用户信息包装
 * @author Linkwork, 276247076@qq.com
 * @since 2016年1月31日
 */
public class MemoUserWrap extends User {

    private static final long serialVersionUID = -8221951436648025707L;

    /**
     * 用户信息
     */
    private MemoUserEntity userEntity;

    /**
     * 获取权限集
     * @param authority
     * @return
     */
    private static Collection<? extends GrantedAuthority> getAuthorityCollection(String authority) {
        ArrayList<GrantedAuthority> athLst = new ArrayList<GrantedAuthority>(1);
        athLst.add(new SimpleGrantedAuthority(authority));
        return athLst;
    }

    /**
     * 
     * @param username
     * @param password
     * @param authorities
     */
    public MemoUserWrap(
            String username,
            String password,
            Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    /**
     * 
     * @param userEntity
     * @param authority
     */
    public MemoUserWrap(MemoUserEntity userEntity, String authority) {
        super(userEntity.getMus_name(), userEntity.getMus_pss(), true, true, true, true, getAuthorityCollection(authority));
        this.userEntity = userEntity;
    }

    public MemoUserEntity getUserEntity() {
        return userEntity;
    }

    public void setUserEntity(MemoUserEntity userEntity) {
        this.userEntity = userEntity;
    }

}
共有 人打赏支持
粉丝 5
博文 116
码字总数 22716
×
抢地主
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: