Spring Security 3.x full start configuration tutorial and its code downloads

Source: Internet
Author: User
Tags object object

Original is not easy, reprint please specify the Source: Spring Security 3.x full start configuration tutorial and its code download

Code Download Address: http://www.zuidaima.com/share/1751865719933952.htm

Spring Security 3.x out for a while, with the Acegi is big different, and 2.x version there are some small differences, there are some documents online, but also someone translate Spring Security 3.x guide, but by reading guide, It is not immediately easy to implement a complete instance.


I spent a little time, based on the previous experience, organized a complete introductory course for the needs of friends for reference.
1, build a Web project, and import all the needed lib, this step is not much to say.
2, configure Web.xml, using spring's mechanism to load:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.4" xmlns= "Http://java.sun.com/xml/ns/j2ee" xmlns : xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://java.sun.com/xml/ns/j2ee http:// Java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <context-param> <param-name> contextconfiglocation </ param-name> <param-value> classpath:applicationcontext*.xml </param-value> </context-param> &L t;listener> <listener-class> Org.springframework.web.context.ContextLoaderListener </listener-class > </listener> <filter> <filter-name> springsecurityfilterchain </filter-name> <filt er-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter -mapping> <filter-name> springsecurityfilterchain </filter-name> <url-pattern>/* </ Url-pattern> </filter-mapping> <welcome-file-list> <welcome-file> login.jsp </welcome-file> </welcome-file-list> </web-app> 

 

The contents of this file I'm sure everyone is familiar with it and don't say much more.

2, to see applicationcontext-security.xml This configuration file, the configuration of spring security is in it:

<?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 "Xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/ Security/spring-security-3.0.xsd ">  

3 to see the implementation of the custom filter:

Package com.robin.erp.fwk.security;

 Import java.io.IOException;
 Import Javax.servlet.Filter;
 Import Javax.servlet.FilterChain;
 Import Javax.servlet.FilterConfig;
 Import javax.servlet.ServletException;
 Import Javax.servlet.ServletRequest;

 Import Javax.servlet.ServletResponse;
 Import Org.springframework.security.access.SecurityMetadataSource;
 Import Org.springframework.security.access.intercept.AbstractSecurityInterceptor;
 Import Org.springframework.security.access.intercept.InterceptorStatusToken;
 Import org.springframework.security.web.FilterInvocation;

 Import Org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class Myfiltersecurityinterceptor extends Abstractsecurityinterceptor implements Filter {private Filterinvocati

 Onsecuritymetadatasource Securitymetadatasource; ~ Methods//=================================================================================================== =====/** *//** * Method-is aCtually called by the filter chain.
 Simply delegates to * the {@link #invoke (filterinvocation)} method. 
 * @param request * The servlet request * @param response * The servlet response * @param chain * The filter chain * * @throws IOException * If the filter chain fails * @throws servletexception * If the filter chain fails/PU Blic void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, Servletexcep
 tion {filterinvocation fi= new filterinvocation (Request, response, chain);
 Invoke (FI);
 Public Filterinvocationsecuritymetadatasource Getsecuritymetadatasource () {return this. securitymetadatasource; Public Class
 Extends Object> Getsecureobjectclass () {return filterinvocation. class; public void Invoke (Filterinvocation fi) throws IOException, servletexception {interceptorstatustoken token= super.
 Beforeinvocation (FI);
 try {fi.getchain (). Dofilter (Fi.getrequest (), Fi.getresponse ()); } finally {super. Afterinvocation (token, NULL);
 } public Securitymetadatasource Obtainsecuritymetadatasource () {return this. securitymetadatasource; public void Setsecuritymetadatasource (Filterinvocationsecuritymetadatasource newsource) {this. Securitymetadatasou
 Rce= Newsource; 
 @Override public void Destroy () {} @Override public void init (Filterconfig arg0) throws servletexception {}}

The most central code of the

is the Interceptorstatustoken token = super.beforeinvocation (FI) in the Invoke method, which checks the permissions before performing the Dofilter, and the specific implementation has been given to Accessdecisionmanager, the following will be described.

4 To see the implementation of the Authentication-provider:

Package com.robin.erp.fwk.security;
 Import java.util.ArrayList;

 Import java.util.Collection;
 Import org.springframework.dao.DataAccessException;
 Import org.springframework.security.core.GrantedAuthority;
 Import Org.springframework.security.core.authority.GrantedAuthorityImpl;
 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;  public class Myuserdetailservice implements Userdetailsservice {@Override public userdetails loaduserbyusername (String username) throws Usernamenotfoundexception, DataAccessException {collection<grantedauthority> auths=
 Newarraylist<grantedauthority> ();
 Grantedauthorityimpl Auth2=newgrantedauthorityimpl ("Role_admin");
 Auths.add (AUTH2); if (Username.equals ("Robin1")) {auths=newarraylist<grantedauthority>();
 Grantedauthorityimpl Auth1=newgrantedauthorityimpl ("Role_robin");
 Auths.add (AUTH1); }//User (string Username, string password, Boolean enabled, Boolean accountnonexpired,//Boolean credentialsnonexpired , Boolean accountnonlocked, collection<grantedauthority> authorities) {User User=new User (username, "Robin", True
 , True, True, true, auths);
 return user;
 }
 
}


In this class, you can read the user's password from the database, the role information, whether the lock, the account is expired, and so on, I think such a simple code will not explain more.

5, for the definition of the access rights of a resource, we initialize the data by implementing the Filterinvocationsecuritymetadatasource interface.

Package com.robin.erp.fwk.security;
 Import java.util.ArrayList;
 Import java.util.Collection;
 Import Java.util.HashMap;
 Import Java.util.Iterator;

 Import Java.util.Map;
 Import Org.springframework.security.access.ConfigAttribute;
 Import Org.springframework.security.access.SecurityConfig;
 Import org.springframework.security.web.FilterInvocation;
 Import Org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
 Import Org.springframework.security.web.util.AntUrlPathMatcher;

 Import Org.springframework.security.web.util.UrlMatcher; 
 /** *//** * * This class should be initialized with the definition of all resources and their corresponding roles * * @author Robin */public class Myinvocationsecuritymetadatasource
 Implements Filterinvocationsecuritymetadatasource {private Urlmatcher urlmatcher= new Anturlpathmatcher ();;

 private static Map <string, Collection <ConfigAttribute>> resourcemap= null;
 Public Myinvocationsecuritymetadatasource () {loadresourcedefine (); } private void LoadresouRcedefine () {resourcemap= new HashMap <string, Collection <ConfigAttribute>> ();
 Collection <ConfigAttribute> atts= New ArrayList <ConfigAttribute> ();
 Configattribute ca= New Securityconfig ("Role_admin");
 Atts.add (CA);
 Resourcemap.put ("/index.jsp", Atts);
 Resourcemap.put ("/i.jap", Atts); 
 }//According to a URL, find out permission configuration the this URL.  Public Collection <ConfigAttribute> GetAttributes (Object object) throws IllegalArgumentException {//Guess object 
 is a URL.
 String url= ((filterinvocation) object). Getrequesturl ();
 Iterator <String> ite= Resourcemap.keyset (). iterator ();
 while (Ite.hasnext ()) {String resurl= ite.next ();
 if (Urlmatcher.pathmatchesurl (URL, resurl)) {return resourcemap.get (Resurl);
 } return null;
 Public Boolean supports (Class <?> clazz) {return true;
 Public Collection <ConfigAttribute> Getallconfigattributes () {return null;
 }

}

Look at the Loadresourcedefine method, where I assume that both index.jsp and i.jsp resources require role_admin role users to access. One of the most central parts of the
class is to provide the corresponding permission definition for a resource, the result of the GetAttributes method return. Note that my example uses the Anturlpathmatcher path matcher to check if the URL matches the resource definition, and you actually have to match it in a regular way, or you can implement a matcher yourself.

6, the rest is the final decision, make a decision, in fact, is also very easy, hehe.

Package com.robin.erp.fwk.security;
 Import java.util.Collection;

 Import Java.util.Iterator;
 Import Org.springframework.security.access.AccessDecisionManager;
 Import org.springframework.security.access.AccessDeniedException;
 Import Org.springframework.security.access.ConfigAttribute;
 Import Org.springframework.security.access.SecurityConfig;
 Import org.springframework.security.authentication.InsufficientAuthenticationException;
 Import org.springframework.security.core.Authentication;


 Import org.springframework.security.core.GrantedAuthority;  public class Myaccessdecisionmanager implements Accessdecisionmanager {//in it, need to compare authentication
 With Configattributes.
 1, an object is a URL, a filter being find permission configuration by the this URL, and pass to here. 2, Check authentication has attribute in permission configuration (configattributes)//3, If not match corresponding
 Authentication, throw a accessdeniedexception. public void Decide (AuthEntication authentication, Object object, Collection<configattribute> configattributes) throws
 Accessdeniedexception, Insufficientauthenticationexception {if (configattributes==null) {return; } System.out.println (Object.ToString ());
 Object is a URL.
 Iterator<configattribute> Ite=configattributes.iterator ();
 while (Ite.hasnext ()) {Configattribute ca=ite.next ();
 String needrole= ((securityconfig) CA). getattribute (); For (grantedauthority ga:authentication.getAuthorities ()) {if (Needrole.equals (Ga.getauthority ())) {//ga is user ' s
 Role.
 Return
 }} throw new Accessdeniedexception ("No Right");
 @Override public Boolean supports (Configattribute attribute) {//TODO auto-generated method stub return true;
 @Override public Boolean supports (Class<?> clazz) {return true;

 }


}

In this class, the most important is the decide method, if there is no definition of the resource, direct release, otherwise, if the correct role is found, which is considered to have permission, and release, otherwise throw new Accessdeniedexception ("No Right"); This will go to the 403.jsp page mentioned above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.