3

Using Remember Me in Shiro

 3 years ago
source link: https://nixmash.com/java/using-remember-me-in-shiro/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In this post I'll cover how to use the Remember Me feature in Apache Shiro. Notice the emphasis is on using Remember Me, or retrieving the remembered credentials of the user on the initial page load of future visits. In other words, if I go to NixMash.com I want to see my name in the top right-hand menubar without logging in.

membme0312a.png

Enabling Remember Me

Here are the main points in enabling Remember Me in Shiro. First (and this is more of a sidebar) we want to pass a Boolean from our login form, so be sure to add the hidden "rememberMe" field in the HTML, otherwise a rememberMe @FormParam will not be passed if the checkbox is cleared and we'll have to test for a null.

membme0312b.png

Now we can pass the true/false rememberMe value to the UserPasswordToken and Shiro will take care of the rest. We can add it with the UserPasswordToken instance or explicitly setRememberMe() as shown below.

membme0312c.png

Using Remember Me

Now we get to the using part of the post where we obtain the Remember Me Shiro Subject credentials on the initial page load of future visits.

I like a Base PageInfo logic described in this NixMash post. We each have our own page loading approaches, but regardless we will add the retrieval of the Remember Me Subject. The key for us is Shiro's SecurityUtils.getSubject().getPrincipals() call. Notice we do NOT have a Shiro Subject Session on the initial page load of a future visit, but we DO have a Shiro Subject in our Remember Me Cookie. With this Subject we can create our CurrentUser object, save it to Session and put it into our Mustache Model (or whatever Page Templating Model we're using at the time.)

membme0312d.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK