10 Minutes Quick Start Shiro Beginners Tutorial

Keywords: Programming Session Shiro Java Spring

Current User

Now we can start doing something that we really care about - performing security operations.

When protecting our applications, the most relevant questions we may ask ourselves are "Who is the current user" or "Is the current user allowed to do XXX?"

When we write code or design user interfaces, it is common to ask these questions: applications are usually built on the background of the user, and you want to reflect (guarantee) functionality based on each user standard.Therefore, the most natural way for us to consider application security is based on the current user.

Shiro's API uses its Subject concept to fundamentally represent the "current user" concept.

In almost all environments, you can get the user currently executing through the following call:

Subject currentUser = SecurityUtils.getSubject();

Use SecurityUtils.getSubject(), we can get the Subject that is currently executing.Subject is a security term that basically means "a specific security view of the user currently executing."It is not called "User" because the word "User" is usually associated with humans.

In the security world, the term "Subject" can be expressed as human, but it can be a third-party process, cron job, daemonaccount, or something similar.It just means "the thing is currently interacting with the software".

For most purposes and purposes, you can think of Subject as Shiro's "User" concept.

getSubject() is called in a stand-alone application and returns a user-data-based Subject at a specific location in the application, and in a server environment (for example, a Web application), it acquires Subjects based on user data associated with the current thread or incoming request.

Current user session

Now that you have a Subject, what can you do with it? If you want to make things available to users in the current session of the application, you can get their session:

Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

Session is a specific instance of Shiro that provides most of the things you often use with HttpSessons, with some additional benefits and There's a big difference: it doesn't require an HTTP environment!

If deployed inside a Web application, the default Session will be based on HttpSession.But in a non-Web environment, like this A simple tutorial application, Shiro will automatically use its Enterprise Session Management by default.This means you will use the same API in your application, at any level, regardless of your deployment environment!This opens up a new world of applications, as any application requiring a session no longer has to be forced to use HttpSession or EJB Stateful Session Beans.Also, any client technology can now share session data.

So now you can get a Subject and their Session.If they are allowed to do something, such as checking roles and privileges, where is "checking" really useful?

Permission Check

Well, we can only do these checks for a known user.Our Subject instance above represents the current user, but who is the current user?Uh, They are anonymous - that is, until they sign in at least once.So let me do the following:

if ( !currentUser.isAuthenticated() ) {
    //collect user principals and credentials in a gui specific manner
    //such as username/password html form, X509 certificate, OpenID, etc.
    //We'll use the username/password example here since it is the most common.
    //(do you know what movie this is from? ;)
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
    //this is all you have to do to support 'remember me' (no config - built in!):
    token.setRememberMe(true);
    currentUser.login(token);
}

That's it!It's as simple as that.

But what happens if their login attempts fail?You can catch specific exceptions to tell you exactly what's happening and allow you to handle them and Respond accordingly:

try {
    currentUser.login( token );
    //if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
    //username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
    //password didn't match, try again?
} catch ( LockedAccountException lae ) {
    //account for that username is locked - can't login.  Show them a message?
}
    ... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
    //unexpected condition - error?
}

You can check for many different types of exceptions or throw your own custom condition exceptions that Shiro may not provide.See also AuthenticationException JavaDoc Get more.

Handy Hint

The safest way to do this is to give users the usual login failure messages, because of course you don't want to help an attacker who tries to break into your system.

Okay, so far, we have a login user.What else can we do?

For example, who are they:

//print their identifying principal (in this case, a username):
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );

We can also test whether they have a specific role:

if ( currentUser.hasRole( "schwartz" ) ) {
    log.info("May the Schwartz be with you!" );
} else {
    log.info( "Hello, mere mortal." );
}

We can also determine whether they have permission to operate on a certain type of entity:

if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

Of course, we can perform extremely powerful instance-level privilege checks -- the ability to determine whether a user has access to a particular type of instance:

if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
    log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'.  " +
                "Here are the keys - have fun!");
} else {
    log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

It's a piece of cake, isn't it?

Finally, when users have finished using the application, they can log off:

currentUser.logout(); //removes all identifying information and invalidates their session too.

summary

Hopefully this tutorial will help you understand how to set up Shiro and Shiro's main design concepts in a basic application.

Focus on the Public Number Java Technology Stack Reply to Interview to get the most comprehensive questions and answers I have compiled for 2020.

Recommend going to my blog to read more:

1.Java JVM, Collections, Multithreaded, New Features Series Tutorial

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA Series Tools Tutorial

4.Latest Interview Questions for Java, Backend, Architecture, Alibaba, etc.

Feel good, don't forget to say yes + forward!

Posted by dkode on Tue, 23 Jun 2020 19:00:54 -0700