Spring-security Customizing the login page &inmemoryauthentication validation

Source: Internet
Author: User

Spring security is a security framework that provides declarative security for spring-based applications. The content of the framework is much more, you can restrict the request path according to the role permission. Today primarily validates the custom login page, making the requested permission check in the memory user store. Gossip Hugh, the following direct discussion of my verification process, if there is a better opinion, you are welcome to correct.

1, the system uses MAVEN for JAR package management, spring with the 5.0 version. First, add spring Security's jar package dependency in the Pom file

  <Dependency>              <groupId>Org.springframework.security</groupId>              <Artifactid>Spring-security-core</Artifactid>              <version>${security-version}</version>          </Dependency>          <Dependency>              <groupId>Org.springframework.security</groupId>              <Artifactid>Spring-security-web</Artifactid>              <version>${security-version}</version>          </Dependency>          <Dependency>              <groupId>Org.springframework.security</groupId>              <Artifactid>Spring-security-config</Artifactid>              <version>${security-version}</version>          </Dependency>  

2. Add the Securityconfig file, extend the Websecurityconfigureradapter class, and override the Configure method. (Websecurityconfigureradapter is the customization of the security framework in the application)

 PackageSimm.spring.web.config;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;Importorg.springframework.security.config.annotation.web.builders.HttpSecurity;Importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;ImportOrg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;ImportOrg.springframework.security.crypto.password.NoOpPasswordEncoder, @Configuration @enablewebsecurity Public classSecurityconfigextendsWebsecurityconfigureradapter {/*** HTTP request processing*/@Overrideprotected voidConfigure (Httpsecurity http)throwsException {http.formlogin (). LoginPage ("/user/login.do"). Defaultsuccessurl ("/free/list.do")//Enable form Login. and (). Authorizerequests (). Regexmatchers ("^ (?! /user/login).) *.do "). Authenticated (). and (). Httpbasic ()//. and (). Requireschannel (). Regexmatchers ("^ (?! /user/login).) *.do "). Requiressecure (). and (). CSRF (). disable ();//temporarily disable CSRF    }    /*** Authorization Verification Service*/@Overrideprotected voidConfigure (Authenticationmanagerbuilder auth)throwsException {/*auth.inmemoryauthentication (). Withuser ("Simm"). Password ("{noop}123"). Roles ("USER"). and (). Withuser ("ad Min "). Password (" {noop}admin "). Roles (" USER "," admin ");*/auth.inmemoryauthentication (). Passwordencoder (Nooppasswordencoder.getinstance ()). Withuser ("Simm"). Password ("123"). Roles ("USER").). and (). Withuser ("admin"). Password ("admin"). Roles ("USER", "admin")); }}

Note: The new version of spring security requires that the encoder be provided for the user configuration or the corresponding encoder error cannot be found. Here is a not very important point of knowledge, if we do not call the Passwordencoder method for the user to verify the encoder, then there is an alternative is to add "{noop}" prefix before the password, tracking source discovery, the framework will automatically resolve the {} key to match the corresponding encoder. Here is a debug diagram that you can see below.

3, add Appinitializer class, the Abstractsecuritywebapplicationinitializer to expand the implementation, the system will automatically insert Springsecurityfilter boot, complete the security of the request to intercept.

 Public class extends Abstractsecuritywebapplicationinitializer   { }

The following is the process of springsecurityfilter in Abstractsecuritywebapplicationinitializer, which can be referenced.

4, add Login control controller. The action is followed by two optional request parameter error,logout. When the login fails, the framework redirects to the login page to add an error parameter. When the call to/logout exits the system, the framework finishes executing the Exit event, cleans up the identity information, redirects back to the login page, and carries a logout parameter.

@Controller @requestmapping ("/USER")//Add the annotations of session information, can realize the map assignment of session information and map@SessionAttributes ("User") Public classUsercontroller {@RequestMapping (value= "/login", method =requestmethod.get) PublicString Login (@RequestParam (value = "error", required =false) String error, @RequestParam (value= "Logout", required =false) String Logout,model Model) {if(Error! =NULL) {Model.addattribute ("MSG", "User name or password error!" "); }        if(Logout! =NULL) {Model.addattribute ("MSG", "Successful exit!" "); }        return"User/login"; }

5, next start to access the system to see the results of the framework application

    • Direct access to non-login pages, the system jumps to the authorized login page because there is no login

    • Verifying logon failures, redirecting back to the login page and automatically carrying the error parameter

    • Verify logon success, redirect to Success page

    • Click to exit the system

The security framework content is extensive, and later attempts to read the functionality of users in the database, custom user checks, HTTPS requests, cross-site request forgery, and more. Today's content is relatively simple, first as the first wave of the stepping stone.

Spring-security Customizing the login page &inmemoryauthentication validation

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.