简单说说Spring Security 使用(附加验证码登录,自定义认证)

先看官方文档:http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/

spring security4已经加入了注解的方式,但是为了比较清晰了解,还是使用了配置的方式。

第一步:web.xml 加入拦截、

复制代码

    
    
    
      springSecurityFilterChain
      org.springframework.web.filter.DelegatingFilterProxy
    
    
      springSecurityFilterChain
      /*
        

复制代码

第二步:编写配置文件:spring-security.xml

复制代码


    
    
    
    
    
        
        
         
    
    
        
            
         
    

复制代码

第三步:编写登录认证函数

复制代码

package com.eshore.upsweb.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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 com.eshore.upsweb.dao.CwSysUserDAO;
import com.eshore.upsweb.model.CwSysUser;
import com.eshore.upsweb.model.CwSysUserRole;

@Service(value="cwSysUserDetailsService")
public class CwSysUserDetailsService implements UserDetailsService{
    
    @Autowired
    CwSysUserDAO cwSysUserDAO;
    
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
         System.out.println("username is " + username);  
        CwSysUser user = cwSysUserDAO.findUser(username);
        List authorities = buildUserAuthority(user.getUserRoles());
        return buildUserForAuthentication(user, authorities);
    }
    
    /**
     * 返回验证角色
     * @param userRoles
     * @return
     */
    private List buildUserAuthority(Set userRoles){
        Set setAuths = new HashSet();
        for(CwSysUserRole userRole:userRoles){
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole().getRoleId().toString()));
        }
        List result = new ArrayList(setAuths);
        return result;
    }
    
    /**
     * 返回验证用户
     * @param user
     * @param authorities
     * @return
     */
    private User buildUserForAuthentication(CwSysUser user,List authorities){
        return new User(user.getUserNo(),user.getPassword(),true,true,true,true,authorities);
    }
    
    /**
     * 
     */
    

}

复制代码

 

第四步:编写登录controller

复制代码

package com.eshore.upsweb.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eshore.upsweb.model.CwSysUser;
import com.eshore.upsweb.model.LoginInfo;
import com.eshore.upsweb.service.CwSysUserService;

@Controller
@RequestMapping(value="/user")
public class CwSysUserController {
    @Autowired
    private CwSysUserService cwSysUserService;
    @Autowired
    private AuthenticationManager myAuthenticationManager;  // 这样就可以自动注入?oh ,mygod ,how can it do so?
    
    @RequestMapping(value="/login",method=RequestMethod.POST) 
    @ResponseBody
    public LoginInfo login(@RequestParam(defaultValue="") String username,@RequestParam(defaultValue="") String password,HttpServletRequest request){
        if(!checkValidateCode(request)){
            return new LoginInfo().failed().msg("验证码错误!");
        }
        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
/*        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CwSysUser.class,"cwSysUser");
        detachedCriteria.add(Restrictions.eq("userNo", username));
        if(cwSysUserService.countUser(detachedCriteria)==0){
            return new LoginInfo().failed().msg("用户名: "+username+" 不存在.");
        }
*/        try {
            Authentication authentication = myAuthenticationManager.authenticate(authRequest); //调用loadUserByUsername
            SecurityContextHolder.getContext().setAuthentication(authentication);
            HttpSession session = request.getSession();
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要,否则验证后将无法登陆
            return new LoginInfo().success().msg(authentication.getName());
        } catch (AuthenticationException ex) {
            return new LoginInfo().failed().msg("用户名或密码错误");
        }
    }
    
    
    
    /**
     * 验证码判断
     * @param request
     * @return
     */
    protected boolean checkValidateCode(HttpServletRequest request) {
        String result_verifyCode = request.getSession().getAttribute("verifyResult")
                .toString(); // 获取存于session的验证值
       // request.getSession().setAttribute("verifyResult", null);  
        String user_verifyCode = request.getParameter("verifyCode");// 获取用户输入验证码
        if (null == user_verifyCode || !result_verifyCode.equalsIgnoreCase(user_verifyCode)) {
            return false;
        }
        return true;
    }
    

}

复制代码

第五步:编写对应的登录jsp

复制代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 


Login
 

  
  





        

电信融合支付平台


文章转自:http://www.cnblogs.com/huangjiandong2012/p/4026634.html?utm_source=tuicool&utm_medium=referral

 

你可能感兴趣的:(待整理)