More gracefully Configure Spring Securiy (using java configuration and ANNOTATIONS)

Source: Internet
Author: User

Spring security uses a series of servlet Filter to provide secure functionality, but with Spring's tips, we just need to configure a filer, Delegatingfilterproxy is a special servlet Filter, which itself does not do much work, just delegate the work to a Javax.servlet.Filter implementation class, which is registered as a bean in the context of the spring Application.

If you've seen a friend who configures spring security with xml, it's tedious to configure spring security with XML based, and it's not easy to learn and get started, but based on Javaconfig and annotations, This configuration is greatly simplified. Let's take a look at how to configure Spring Security in Java

First we need to configure delegatingfilterproxy, we just have to expand a new class, the class implements the webapplicationinitializer, So spring will find it and use it to register Delegatingfilterproxy in the Web Container.

  

 public class extends Abstractsecuritywebapplicationinitializer {}

Next we need to enable the Web security feature, and just to extend a class, Spring Security must be configured in a bean that implements websecurityconfigurer, or expand Websecurityconfigureradapter. In the context of the spring application, any bean that implements Websecurityconfigureradapter can be used to configure spring Security. The common configuration has been affixed, and all the corresponding comments are Written.

 

@Configuration @enablewebsecurity public classSecurityconfigextendsWebsecurityconfigureradapter {@AutowiredPrivateUserdetailserviceimpl userdetailservice; //the key to fine-grained security control for each request is to overload the method@Overrideprotected voidConfigure (httpsecurity Http)throwsException {http. authorizerequests ()//method of the object returned by the method to configure the Request-level security details. antmatchers ("/login"). Permitall ()//no interception for login path. antmatchers ("/show"). Authenticated ()//authenticated () indicates allowed user access. and (). formlogin ()//Configure the login page. LoginPage ("/login")//access path to the login page. Loginprocessingurl ("/check")//the path of the form submission under the login page. Failureurl ("/login")//path to jump after login failed. Defaultsuccessurl ("/show")//path of default jump after successful login. and (). csrf ()//Enable Anti-cross-site pseudo-request attack, enabled by default. and (). logout ()//User exit Action. Logouturl ("/logout")//the user exits the path that is accessed and needs to use the Post method. Permitall (). Logoutsuccessurl ("/login?logout=true"). and (). authorizerequests ()//                    //define a configuration method for path protection//. Antmatchers (httpmethod.get, "/admin")//. Authenticated (). antmatchers (httpmethod.get, "/message/**", "/object/**"). hasrole ("USER"). anyrequest (). permitall (). and (). rememberme ()//Enable remember me feature. Tokenvalidityseconds (2419200)            ; }    //Configure the filter chain for spring security@Override public voidConfigure (websecurity Web)throwsException {Super. Configure (web); }    //Configuring the User-detail service@Overrideprotected voidConfigure (authenticationmanagerbuilder Auth)throwsException {auth.userdetailsservice (userdetailservice). passwordencoder (NewStandardpasswordencoder ("53cr3t"))//Password Encryption Method        ;//auth.inmemoryauthentication ()//Built-in Users//. withuser ("user"). password ("user") . roles (" user");    }}

There are a few points to note that if you configure spring security based on javaconfig and annotations in an xml-configured SPRINGMVC environment, you only need to ensure that the spring context can scan to the two classes mentioned Above.

If you use the Spring form label under the JSP page, the label will automatically add the hidden CSRF token tag by default, which is Anti-cross-site pseudo-request attack, and if you do not use Spring's form label, you will need to manually add the following label, especially for logout logout form submission , the following must be protected within the form tag .

  

<type= "hiden"            name= "${_csrf.parametername}"             Value= "${_csrf.token}"}

Here is the login page

  

<%@ Page ContentType="Text/html;charset=utf-8"language="Java" %><%@ taglib Prefix="SF"URI="Http://www.springframework.org/tags/form" %><HTML><Head>    <title>Login</title></Head><Body><Sf:formAction= "check"Method= "post"CommandName= "user" >User Name:<Sf:inputPath= "username"></Sf:input>password:<Sf:passwordPath= "password"></Sf:password>    <inputID= "remember_me"name= "remember-me"type= "checkbox">    <label for= "remember_me"class= "inline">Remember Me</label>    <inputtype= "submit"value= "submit" ></Sf:form></Body></HTML>

Log Out page

  

<%@ Page Language="Java"ContentType="Text/html;charset=utf-8"pageencoding="UTF-8"%><%@ taglib Prefix="SF"URI="Http://www.springframework.org/tags/form" %><HTML><Head>    <title>User Manager</title></Head><Body>     <Sf:formID= "logoutform"Action= "${ctx}/logout"Method= "post"><ahref="#"onclick= "document.getelementbyid" (' logoutform '). submit (); ">Cancellation</a></Sf:form></Body></HTML>

If we want to configure custom authentication and authorization services, we need to implement Userdetailsservice

  

 public classUserdetailserviceimplImplementsUserdetailsservice {Private StaticLogger Logger=logger.getlogger (userdetailserviceimpl.class); @AutowiredPrivateIuserservice userservice; @AutowiredPrivateIroleservice roleservice; @Override publicUserdetails loaduserbyusername (String Username)throwsusernamenotfoundexception {logger.info ("=========== Authorized ============"); User User=NULL; List<Role> role=NULL; Try{ user = Userservice.finduserbyusername (username); Role= roleservice.listrolebyuserid (user.getid ()); Logger.info ("user role is:" +role); } Catch(baseexception E) {e.printstacktrace (); } List<GrantedAuthority> list=NewArraylist<grantedauthority>(); List.add (NewSimplegrantedauthority ("role_" +role)); Org.springframework.security.core.userdetails.User Authuser=Neworg.springframework.security.core.userdetails.User (user.getusername (), user.get            Password (), list); returnauthuser; }}

This configuration subdivides the security level into the Role. The overridden method comes with a parameter of login username, which obtains the user from the database, and the corresponding permissions, eventually by the user, password, Permissions are passed in and instantiated org.springframework.security.core.userdetails.User, thus authorizing the End. Configure the security path or permissions in the method according to the permissions obtained and bound in the above method. At this point, we can secure the path to security Rights.

More gracefully Configure Spring Securiy (using java configuration and ANNOTATIONS)

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.