Shiro implements RememberMe functionality

This article describes and implements the RememberMe function in Shiro.



Shiron provides the ability to remember me, such as when visiting websites like Taobao, closing the browser and remembering who you are the next time you open it, and accessing it without having to sign in again the next time you visit.

The basic process is as follows:

1. First select RememberMe on the login page and then log in successfully. If the browser logs in, RememberMe's Cookie is usually written to the client and saved.

2. Close the browser and reopen it; you will find that the browser still remembers you;

3. Access the general web server or know who you are and can access it normally;

4. But when we visit Taobao for example, if we want to view my order or make payment, we still need to authenticate at this time to make sure the current user is still you.

About interceptors

To access general web pages, such as a personal home page, we use the user interceptor, which can be accessed successfully as long as the user logs on (isRemembered()==true||isAuthenticated()==true);

Visit special web pages, such as my order, submit order page, we use authc interceptor, authc interceptor will determine if the user is passing


Logged in, if it is released, otherwise you will jump to the login page and ask you to log in again.

About cookie s for rememberMe

shiro automatically serializes and encrypts user objects. When requested, it is able to obtain the user objects after deserialization and decryption.

When rememberMe==false is set, the rememberMe cookie is automatically emptied.

What if you don't want to sign in automatically?

Call shiro's logout() method, which eliminates automatic login.


Realization Add Configuration in

Be careful:
The incoming parameter is byte[], which is 16 bits long, otherwise an Unable to init cipher instance error will be reported: Unable to initialize the password instance.
/** * cookie object; * @return */ public SimpleCookie rememberMeCookie(){// This parameter is the name of the cookie, corresponding to the name of the front-end checkbox = rememberMe * SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); the //cookie takes effect for 30 days, in units of seconds;;simpleCookie.setMaxAge(2592000);return simpleCookie;}
/** * cookie management object; remember my feature * @return */ public CookieRememberMeManager rememberMeManager(){CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();; cookieRememberMeManager.setCookie(rememberMeCookie());CooKieRememberMeManager.setCipherKey("ZHANGXIAOHEI_CAT ".getBytes();" return cookieRememberMeManager;}

Inject into SecurityManager

@Bean(name="securityManager")  public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();    //Associate realm Security Manager.setRealm(userRealm); //Use Remember Me)Security Manager.setRememberMeManager(rememberMeManager (); > return securityManager;}

Modify login pageLogin.html

<body><h3 th:text="${msg}" style="color: red"></h3>    <form method="post" action="login">         User:<input type="text" id="userName" name="userName"/><br/>         Code:<input type="password" id="password" name="password"/><br/>         <input type="checkbox" name="rememberMe">Remember me<br>        <input type="submit" value="Sign in" id="sender" >     </form></body>

@RequestMapping(value="/login",method = RequestMethod.GET)  public String toLogin(Model model) {    Subject subject = SecurityUtils.getSubject();      System.out.println(subject.isRemembered());    System.out.println(subject.isAuthenticated());    if(subject.isRemembered()){      System.out.println("-------------------------------------------------");            System.out.println("Authentication Successful");            DzmHisMember member = (DzmHisMember)subject.getPrincipal();            model.addAttribute("member",member);            return "redirect:/toHome";        }    return "login";  }
 @RequestMapping(value="/login",method = RequestMethod.POST)  public String login(String userName,String password,boolean rememberMe,Model model)  {    /**     * Write authentication operations using Shiro *///1. Get Subject; Subject subject =SecurityUtils.getSubject(); //2. Encapsulate user data; UsernamePasswordToken token = new UsernamePasswordToken(userName,password);//3. Execute login method; try {System.out.println(rememberMe);)token.setRememberMe(rememberMe);)subject.login(token);//Login succeeded, jump to home page "return redirect:/toHome;} catch (UnknownAccountException) {//Login failure: username does not exist model.addAttribute("msg", "user name does not exist"); return "login";} catch (IncorrectCredentialsException) {// Logon failure: incorrect password]model.addAttribute("msg", "password error"); return "login";}}

  • The previous login checked Remember Me, then isRemembered()==true at this login (if rememberme was last set, this login will not trigger the login() method in the action, that is, it will go directly into the login state).

  • login() with shiro denotes authenticated login. That is, authentication==true. Access is highest.

  • rememberMe==true, then no action will be entered. All user-controlled pages or paths can be accessed. But authc-controlled faces or paths cannot be accessed.

Here's a key point:

subject.isAuthenticated()==true, thenSubject.isRemembered() ==false;

The opposite is true.



Enter in Address Bar http://localhost:8080/hospital/login , check "Remember Me" for the first login, close the page after successful login, and enter it in the address bar

http://localhost:8080/hospital/login It goes directly to the home page instead of the landing page, and the console output is as follows:

This concludes the article.Welcome to my public number: The dark stars surge.

Tags: Java Shiro Web Server

Posted on Thu, 04 Jun 2020 15:23:18 -0700 by V_dirt_God