Read the Official document first: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/
Spring Security4 has added a way to annotate, but in order to get a clearer picture, the configuration is used.
The first step: Web. XML joins the interception,
<!--configuration Springsecurityfilter-- <filter> <filter-name>springsecurityfilterchain</ Filter-name> <filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class > </filter> <filter-mapping> <filter-name>springsecurityfilterchain</ filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Step Two: Write the configuration file: Spring-security.xml
<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 "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/security HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/SECURITY/SPRING-SECU Rity-3.2.xsd "> Step three: Write the login authentication function
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 Cwsysuse Rdao Cwsysuserdao; @Override public userdetails loaduserbyusername (String UsernamE) throws Usernamenotfoundexception {System.out.println ("username is" + username); Cwsysuser user = Cwsysuserdao.finduser (username); List<grantedauthority> authorities = Builduserauthority (User.getuserroles ()); return builduserforauthentication (user, authorities); }/** * Returns validation role * @param userroles * @return */private list<grantedauthority> Builduseraut Hority (set<cwsysuserrole> userroles) {set<grantedauthority> setauths = new hashset<grantedauthority& gt; (); for (Cwsysuserrole userrole:userroles) {setauths.add (New simplegrantedauthority (Userrole.getrole (). GetRoleId (). t Ostring ())); } list<grantedauthority> result = new arraylist<grantedauthority> (setauths); return result; }/** * Returns the authenticated user * @param user * @param authorities * @return */private user Builduserforauth Entication (Cwsysuser user,list<grantEdauthority> authorities) {return new User (User.getuserno (), User.getpassword (), true,true,true,true,authorities) ; } /** * */ }
Fourth step: Write the login 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; So you can inject it automatically? Oh, mygod, how can it do? @RequestMapping (value= "/login", Method=requestmethod.post) @ResponseBody public logininfo Login (@RequestParam (defau Ltvalue= "") string username, @RequestParam (defaultvalue= "") string Password,httpservletrequest request) {if (!checkva Lidatecode (Request)) {return new Logininfo (). Failed (). MSG ("CAPTCHA Error! "); } username = Username.trim (); Usernamepasswordauthenticationtoken authrequest = new Usernamepasswordauthenticationtoken (username, password);/* De Tachedcriteria Detachedcriteria = Detachedcriteria.forclass (Cwsysuser.class, "Cwsysuser"); Detachedcriteria.add (Restrictions.eq ("Userno", username)); if (Cwsysuserservice.countuser (DetAchedcriteria) ==0) {return new Logininfo (). Failed (). MSG ("Username:" +username+ "does not exist."); }*/try {Authentication authentication = myauthenticationmanager.authenticate (authrequest);//Call Loaduse Rbyusername Securitycontextholder.getcontext (). Setauthentication (authentication); HttpSession session = Request.getsession (); Session.setattribute ("Spring_security_context", Securitycontextholder.getcontext ()); This is very important, otherwise the verification will not be able to log on to return new Logininfo (). Success (). MSG (Authentication.getname ()); } catch (Authenticationexception ex) {return new Logininfo (). Failed (). MSG ("User name or password error"); }}/** * Verification code judgment * @param request * @return */protected Boolean Checkvalidatecode (Htt Pservletrequest request) {String Result_verifycode = Request.getsession (). getattribute ("Verifyresult") . toString (); Gets the validation value stored in session//Request.getsession (). SetAttribute ("Verifyresult ", NULL); String User_verifycode = Request.getparameter ("Verifycode");//Get user Input Verification code if (null = = User_verifycode | |!result_ver Ifycode.equalsignorecase (User_verifycode)) {return false; } return true; } }
Fifth step: Write the corresponding login JSP
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "%><! DOCTYPE html ">Simply say Spring Security use (additional verification code login, custom authentication)