Spring Security Framework Remember Me,demo learning

Source: Internet
Author: User

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/50018001 not allowed to reprint without the Bo master.
Bo main address is: Http://blog.csdn.net/freewebsys

1,spring Security

Spring Security, formerly known as Acegi Security, is the framework used in the Spring project team to provide secure authentication services.

The most used on this side of the security framework is spring security.
The Forum information is more substantial.

A buddy wrote an example that was developed using the spring secuirty3.
http://www.mkyong.com/spring-security/spring-security-remember-me-example/

Spring Security related content:
http://www.mkyong.com/tutorials/spring-security-tutorials/

Official API:
Http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity.html

First download the source code according to the demo, unzip the import project.

The code is simple, 4 JSP files, one controller.
Database uses MySQL to create databases and tables:

 CREATETABLE users (username VARCHAR)not  NULL , password VARCHAR ($)  not null , enabled TINYINT  not null DEFAULT 1
      , PRIMARY KEY (username));  CREATE TABLEUser_roles (user_role_idint( One) not NULLAuto_increment, usernamevarchar( $) not NULL, rolevarchar( $) not NULL,PRIMARY KEY(user_role_id),UNIQUE KEYUni_username_role (Role,username),KEYFK_USERNAME_IDX (username),CONSTRAINTFk_usernameFOREIGN KEY(username)REFERENCESUsers (username)); INSERT  into Users (username,password,enabled)VALUES (' Mkyong ',' 123456 ', true); INSERT  into Users (username,password,enabled)VALUES (' Alex ',' 123456 ' , true); INSERT  into user_roles (username, role)VALUES (' Mkyong ', ' Role_user '); INSERT  into user_roles (username, role)VALUES (' Mkyong ', ' role _admin ');insert  INTO  user _roles (username, role) values  ( ' Alex ' ,  ' role_user ' ); create  TABLE  Persistent_logins (username varchar  (64 ) not  null , Series varchar  (64 ) not   Null , token varchar  (64 ) not  null , last_used timestamp  not  null ,  PRIMARY  key  (series)); 

Where Persistent_logins is the record user remember me.
Use token for user name.
The specific operation of the effect, in the demo has been introduced in the very clear.

There will be a cookie after landing using remember me.

When I quit, it's gone.
Returns 403 when no permissions are used.

Configure Authentication-manager

<authentication-manager ;  <authentication-provider  >  <jdbc-user-service  data-source-ref  =" DataSource " users-b Y-username-query  = "Select Username,password, enabled from users where Username=?"  authorities-by-username-query  = "SELECT username, Role from user_roles where username =? "/>  </authentication-provider  >  </authentication-manager ;  

First configure the data source, according to the User Name Password query table users, query and then follow the user name and query permissions. Returns a list of permissions.
At that time remember me when the situation landed directly query Persistent_logins, with token Exchange user login name, in the user login name query user information, permissions.

But in the Internet application, the general user is a privilege. There's no use of the role table, it's not so complicated.

3, Custom Authenticationprovider

First implement a userdetailsservice. Database queries should be performed here. Then return to Userdetails. Here omit directly create an object, the password is written dead, as long as is the landing successful ride return Role_user permissions.

public  class  myuserdetailsservice   Implements  userdetailsservice  { @ Override  public  userdetails loaduserbyusername< /span> (String userName) throws  usernamenotfoundexception {ArrayList l ist = new  ArrayList (); List.add (new  simplegrantedauthority ( "ROLE_USER" )); User Details = new  User ( "demo" , " demo ", list); return  details; }}

And then implement a Authenticationprovider

 Public  class myauthenticationprovider implements authenticationprovider {    @AutowiredUserdetailsservice Userdetailsservice; PublicAuthenticationAuthenticate(Authentication authentication)throwsauthenticationexception {//usernameSystem.out.println ("User name:"+ Authentication.getname ());//passwordSystem.out.println ("Password:"+ authentication.getcredentials ()); System.out.println ("Getprincipal:"+ Authentication.getprincipal ()); System.out.println ("Getauthorities:"+ authentication.getauthorities ()); System.out.println ("Getdetails:"+ authentication.getdetails ()); Userdetails userdetails = (userdetails) This. Userdetailsservice.loaduserbyusername (Authentication.getname ());if(Userdetails! =NULL&& Userdetails.getpassword ()! =NULL&&!userdetails.getpassword (). Equals (Authentication.getcredentials ())) {//If the password is not the same, throw the exception directly.             Throw NewUsernamepassworderrorexception ("User name or password is wrong!" "); }//If the user name password is correct. Usernamepasswordauthenticationtoken result =NewUsernamepasswordauthenticationtoken (Userdetails, Authentication.getcredentials (), UserDetails.getAuthoriti ES ());returnResult } Public Boolean supports(Class authentication) {return true; } Public void Setuserdetailsservice(Userdetailsservice Userdetailsservice) { This. Userdetailsservice = Userdetailsservice; }}

Here, if the user name password is wrong, throw a custom exception directly:

publicclass UserNamePasswordErrorException extends AuthenticationException {    publicUserNamePasswordErrorException(String msg) {        super(msg);    }}

Then modify the configuration:

    <bean id= "userdetailsservice" class=" Com.demo.security.auth.MyUserDetailsService "/>    <bean id= "myauthenticationprovider" class=" Com.demo.security.auth.MyAuthenticationProvider ">        < property name="Userdetailsservice" ref="Userdetailsservice" />    </Bean><authentication-manager>        <authentication-provider ref="Myauthenticationprovider">        </authentication-provider>    </Authentication-manager>
4, summary

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/50018001 not allowed to reprint without the Bo master.
Bo main address is: Http://blog.csdn.net/freewebsys

Spring Security on the safety of the configuration as long as it is good, very convenient.
But only a preliminary study was carried out. For example, the problem of encryption, such as the name of the cookie, you need to continue to study.

Spring Security Framework Remember Me,demo learning

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.