Subject of Shiro actual combat series (10)

There is no doubt that the most important concept in Apache Shiro is subject. " Subject 'is just a security term, which refers to the specific security "view" of the application user. A Shiro subject instance represents the security state and operation of a single application user.

These operations include:

authentication(login)

authorization(access control)

session access

logout

We originally wanted to call it "user" because it was "very meaningful", but we decided not to do so: too many applications have their own user classes / frameworks, and we don't want to conflict with them. In addition, in the field of security, the term "subject" is actually a recognized term.

Shiro's API provides subject centered programming paradigm support for applications. When coding application logic, most application developers want to know who is currently executing. Although applications can usually find any user through their own mechanism (userservice, etc.), when it comes to security, the most important question is "who is the current user?".

Although any subject can be captured by using securitymanager, only the application code based on the current user / subject is more natural and intuitive.

The currently executing subject

In almost all environments, you can get the currently executed subject by using org apache. shiro. SecurityUtils:

The getsubject () method calls an independent application. The application can return a subject based on user data in a specific location of the application. In the server environment (such as a web application), it obtains the subject based on user data related to the current thread or incoming request.

When you get the current subject, what can you do with it?

If you want to make things available to users in their current session, you can get their session:

Session is a specific instance of Shiro. It provides most of the things you often use with httpsessions, but it has some additional benefits and a big difference: it does not need an HTTP environment! If deployed inside a web application, the default session will be based on httpsession. However, in a non web environment, like this simple QuickStart, Shiro will automatically use its enterprise session management by default. This means that you can use the same API in your application at any tier, regardless of the deployment environment. This opens a new world of applications, because any application that needs session is no longer forced to use httpsession or EJB stateful session beans. Moreover, any client technology can now share session data. Therefore, you can now get a subject and their session. What about really useful things like checking, if they are allowed to do something - such as checking roles and permissions? Well, I can only do these checks on known users. Our subject instance represents the current user, but who is the actual current user? Well, they are anonymous - that is, until they log in at least once. So let's do something like this:

That's it! It can't be simpler. But what happens if their login attempt fails? You can catch a variety of specific exceptions to tell you what happened:

You, as an application / GUI developer, can choose whether to display messages to end users based on exceptions (for example, "there is no account corresponding to this user name in the system"). There are many different kinds of exceptions for you to check, or you can throw your own custom exceptions, which may not be provided by Shiro. For details, see Javadoc for authenticationexception. Well, now that we have a login user, what else can we do? For example, who are they:

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

This simple API contains 90% of what Shiro end users will handle when using Shiro.

Custom subject instances adds a new feature in Shiro 1.0, which can construct custom / temporary subject instances under special circumstances.

Special Use Only! You should always call subjectutils Getsubject() to get the currently executing subject; Creating a custom subject instance should only be done under special circumstances.

This can be useful in some "special cases": system startup / boot - when there is no user system interaction, the code should be executed as a 'system' or daemon user. It is worthwhile to create a subject instance to represent a specific user, In this way, the boot code can be used by the user (such as admin). This practice is encouraged because it ensures that the utility / system code is executed in the same way as an ordinary user to ensure that the code is consistent. This makes the code easier to maintain because you don't have to worry about the custom code block of the system / daemon scheme. Integration testing - you may want to create a subject instance, which can be set when necessary Used in the test. Refer to the test documentation for more information. The work of the daemon / background process -- when a daemon or background process executes, it may need to be executed as a specific user.

Well, assuming you still need to create a custom subject instance, let's see how to do it:

Subject. Builder

Subject. The builder is designed to make it very easy to create a subject instance without knowing the construction details. The simplest use of builder is to construct an anonymous, session less instance.

The default subject shown above The builder parameterless constructor will pass securityutils The getsubject () method uses the securitymanager currently accessible to the application. You can also specify the securitymanager instance used by additional constructors, if you need:

All other subjects Builder methods can be called before the buildsubject () method to provide context on how to construct a subject instance. For example, if you have a session ID and want to get the subject that "owns" the session (assuming that the session exists and has not expired):

Similarly, if you want to create a subject instance to reflect a certain identity:

You can then use the constructed subject instance to call it as expected. But please note: the constructed subject instance will not be automatically bound to the application (thread) due to further use of the application (thread). If you want it to easily call securityutils. Getsubject() for any code, you must ensure that the created subject has a thread associated with it.

As mentioned above, thread association only constructs a subject instance and is not associated with a thread -- a common necessary condition is that any changes to securityutils during thread execution Whether the call to getsubject () works properly. There are three ways to ensure that a thread is associated with a subject:

(1) Automatic association - via sujbect The execute * method executes a callable or runnable method, which will automatically bind and unbind the subject to the thread before and after the callable / runnable exception.

(2) Manual Association - you can manually bind and unbind the subject instance in the currently executing thread. This is often very useful for framework developers.

(3) Different thread -- by calling subject The associatewith * method associates the callable or runnable method with the subject, and then the returned callable / runnable method is executed in another thread. This is the preferred method if you need to perform work on another thread for the subject.

The most important thing to understand thread correlation is that two things must always happen:

1. Subject is bound to the thread, so it is available at all execution points of the thread. Shiro does this through its threadstate mechanism, which is an abstraction on ThreadLocal.

2. Subject will be unbound at a certain point, even if the execution result of the thread is wrong. This ensures that the thread remains clean and clears any previous subject state in the pooled / reusable threading environment. These principles ensure that they occur in the above three mechanisms. Next, explain their usage.

Automatic association

If you only need a subject temporarily associated with the current thread, and you want thread binding and cleanup to occur automatically, the direct execution of subject callable or runnable is exactly what you need. In subject After the execute call returns, the current thread is guaranteed to be in the same state as before execution. This mechanism is the most widely used of the three.

For example, let's assume that you have some logic to execute at system startup. You want to execute code blocks as a specific user, but once the logic is complete, you want to ensure that the thread / environment automatically returns to normal. You can call subject Execute * method to:

This method is also very useful in framework development. For example, Shiro's support for secure spring remoting ensures that remote calls can be executed as a specific subject:

Manual Association

Although subject The execute * method can automatically clean up the thread state after they return, but there may be cases where you want to manage the threadstate yourself. When combined with w / Shiro, this is almost always used at the framework development level, but it is rarely used in the bootstrap / daemon scenario (the subject. Execute (label) example above is used more frequently).

The best practice is to ensure cleaning in the try / finally block:

Interestingly, this is subject The execute * method actually does -- they just automatically execute this logic before and after the callable or runnable is executed. Shiro's shirofilter performs almost the same logic for Web Applications (shirofilter uses the implementation of Web specific threadstate, which is beyond the scope of this section).

A Different Thread

If you have a callable or runnable instance to execute as a subject, and you execute callable or runnable yourself (or hand it over to the thread pool or executor or excutorservice), you should use the subject. Associatewith * methods. These methods ensure that the subject is retained in the final thread of execution and that the subject is accessible.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>