Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use SpringMVC Shiro

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge of how to use SpringMVC Shiro. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

one。 Introduction

Apache Shiro is a security framework of Java. At present, more and more people are using Apache Shiro, because it is quite simple, and it may not be as powerful as Spring Security compared to Spring Security, but it may not require so complex things in actual work, so using a small and simple Shiro is sufficient. There is no need to struggle with which of the two is better, it would be better to solve the project problem more easily.

Shiro can easily develop good enough applications, which can be used not only in JavaSE environment, but also in JavaEE environment. Shiro can help us with authentication, authorization, encryption, session management, integration with Web, caching, etc. That's what we want, and Shiro's API is very simple.

two。 Basic function

Authentication: authentication / login to verify whether the user has the appropriate identity

Authorization: authorization, that is, permission verification, to verify whether an authenticated user has a certain permission; that is, to determine whether a user can do something, such as verifying whether a user has a role. Or fine-grained verification of whether a user has certain permissions on a resource.

Session Manager: session management, that is, after the user logs in, there is a session, and all its information is in the session before exiting. The session can be in a normal JavaSE environment or in a Web environment.

Cryptography: encrypt, protect the security of data, such as password encrypted storage to the database, rather than plaintext storage

Web Support:Web support, which can be easily integrated into Web environment

Caching: cache, for example, after a user logs in, their user information, roles / permissions do not have to be checked every time, which can improve efficiency.

Concurrency:shiro supports concurrent verification of multithreaded applications, that is, if you open another thread in one thread, permissions can be propagated automatically.

Testing: provide testing support

Run As: allows one user to access pretending to be another user (if they allow it)

Remember Me: remember me, this is a very common feature, that is, after logging in once, you don't have to log in next time.

Keep in mind that Shiro does not maintain users or permissions; we need to design / provide these ourselves; and then inject them into Shiro through the appropriate interface.

You can see that the object that the application code interacts with directly is Subject, that is, the external API core of Shiro is the meaning of each API of Subject;:

Subject: the subject represents the current "user". This user is not necessarily a concrete person, and everything that interacts with the current application is Subject, such as web crawlers, robots, etc.; that is, an abstract concept; all Subject are bound to SecurityManager, and all interactions with Subject are delegated to SecurityManager;. Subject can be regarded as a facade; SecurityManager is the actual executor.

SecurityManager: security manager; that is, all security-related operations interact with SecurityManager; and it manages all Subject;. You can see that it is the core of Shiro, and it is responsible for interacting with other components described later. If you have studied SpringMVC, you can think of it as a DispatcherServlet front-end controller.

Realm: domain, Shiro obtains security data (such as users, roles, permissions) from Realm, that is, if SecurityManager wants to verify the user's identity, it needs to obtain the corresponding user from Realm for comparison to determine whether the user's identity is legitimate; it also needs to get the corresponding user's role / authority from Realm to verify whether the user can operate; Realm can be regarded as a DataSource, that is, a secure data source.

In other words, for us, the simplest Shiro application:

1. The application code is authenticated and authorized by Subject, and Subject is entrusted to SecurityManager.

2. We need to inject Realm into the SecurityManager of Shiro, so that SecurityManager can get legitimate users and their permissions to judge.

As can be seen from the above, Shiro does not provide maintenance users / permissions, but allows developers to inject it themselves through Realm

Subject: subject. You can see that the principal can be any "user" that can interact with the application.

SecurityManager: the equivalent of DispatcherServlet in SpringMVC or FilterDispatcher; in Struts2 is the heart of Shiro; all specific interactions are controlled by SecurityManager; it manages all Subject and is responsible for authentication and authorization, as well as session and cache management.

Authenticator: authenticator, responsible for subject authentication. This is an extension point. If you think Shiro is not good by default, you can customize its implementation. It requires authentication policy (Authentication Strategy), that is, under what circumstances the user's authentication has been passed.

Authrizer: an authorizer, or access controller, that determines whether the principal has the authority to operate accordingly; that is, to control which functions in the application the user can access

Realm: there can be one or more Realm, which can be thought of as a secure entity data source, that is, it can be used to obtain a security entity; it can be implemented by JDBC, LDAP, memory, etc.; it is provided by the user; Note: Shiro does not know where and in what format your user / permissions are stored; so we generally need to implement our own Realm in our applications.

SessionManager: if you have written about Servlet, you should know the concept of Session. Session needs someone to manage its life cycle. This component is SessionManager;, and Shiro can be used not only in Web environment, but also in ordinary JavaSE environment, EJB environment and so on. So, Shiro abstracts its own Session to manage the data between the agent and the application. In this case, for example, when we use it in Web environment, it starts as a Web server. Then there is an EJB server; when you want to put the session data of the two servers in one place, you can implement your own distributed session (such as putting the data to the Memcached server)

SessionDAO:DAO has been used by everyone. Data access objects, CRUD for conversations, for example, if we want to save Session to a database, we can implement our own SessionDAO and write to the database through JDBC; for example, if we want to put Session into Memcached, we can implement our own Memcached SessionDAO; and use Cache for caching in SessionDAO to improve performance.

CacheManager: cache controller to manage caches such as users, roles, permissions, etc. Because these data are rarely changed, the performance of access can be improved by putting them in the cache.

Cryptography: password module, Shiro enhances some common encryption components such as password encryption / decryption.

three。 Use Maven package 1.2.3 passwordRetryCache; public RetryLimitHashedCredentialsMatcher (CacheManager cacheManager) {/ / passwordRetryCache = cacheManager.getCache ("passwordRetryCache");} @ Override public boolean doCredentialsMatch (AuthenticationToken token, AuthenticationInfo info) {/ / Strin matches; String username = (String) token.getPrincipal () / / retrycount + 1 Object element= EhcacheUtil.getItem (username); if (element= = null) {EhcacheUtil.putItem (username, 1); element=0;} else {int count=Integer.parseInt (element.toString ()) + 1; element=count; EhcacheUtil.putItem (username,element);} AtomicInteger retryCount = new AtomicInteger (Integer.parseInt (element.toString () If (retryCount.incrementAndGet () > 5) {/ / if retrycount > 5 throw throw new ExcessiveAttemptsException ();} boolean matches = super.doCredentialsMatch (token, info); if (matches) {/ / clear retrycount EhcacheUtil.removeItem (username);} return matches;}} 7. Exit login / * * exit login * @ return * / @ RequestMapping ("/ logout") public String logout () {Subject subject = SecurityUtils.getSubject (); Session session = subject.getSession (); if (subject.isAuthenticated ()) {System.out.println (session.getLastAccessTime ()); subject.logout ();} else if (subject.isRemembered ()) {subject.logout ();} return "home" } eight. Create Ecache cache and aging

1.spring-shir configuration ecache

2.Ecache utility class

Public class EhcacheUtil {private static final CacheManager cacheManager = CacheManager.getInstance (); / * create an ehcache cache with a validity period of 1 hour * / private static Cache cache = new Cache (new CacheConfiguration ("systemCache", 5000) .timeoutMillis () .timeoutMillis (60 * 60)); static {cacheManager.addCache (cache) } public static void putItem (String key, Object item) {if (cache.get (key)! = null) {cache.remove (key);} Element element = new Element (key, item); cache.put (element);} public static void removeItem (String key) {cache.remove (key) } public static void updateItem (String key, Object value) {putItem (key, value);} public static Object getItem (String key) {Element element= cache.get (key); if (nullable disabled element) {return element.getObjectValue ();} return null;}} above is all the content of this article "how to use SpringMVC Shiro". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report