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 manage Rights in Springboot Integration Shiro

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to manage rights in Springboot integration Shiro, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The authorization process of Shiro is similar to the authentication process:

Create SecurityManager Security Manager

Subject principal executes authorization with authorization information and requests to SecurityManager

SecurityManager Security Manager invokes Authorizer authorization

Authorizer combines the authorization information transmitted by the subject step by step with the data in Realm, authorization.

(1) We have configured the SecurityManager security manager in the ShiroConfig configuration class

/ * configure Shiro core security manager SecurityManager * SecurityManager security manager: all security-related operations interact with SecurityManager; and it manages all Subject; to interact with other components described later. (similar to the DispatcherServlet controller in SpringMVC) * / @ Bean public SecurityManager securityManager () {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); / / give the custom realm to the SecurityManager management securityManager.setRealm (new CustomRealm ()); return securityManager;}

(2) the authorization method doGetAuthorizationInfo in the custom Realm class CustomRealm is rewritten below

@ Override / * Authorization * / protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principal) {/ / get the currently logged-in user User user = (User) principal.getPrimaryPrincipal (); / / authorize SimpleAuthorizationInfo simpleAuthorizationInfo through SimpleAuthenticationInfo = new SimpleAuthorizationInfo (); / / add role simpleAuthorizationInfo.addRole (user.getRole ()) / / add permission simpleAuthorizationInfo.addStringPermissions (user.getPermissions ()); return simpleAuthorizationInfo;}

The above mainly adds the roles and permissions owned by the current user through addRole and addStringPermissions in SimpleAuthorizationInfo, and compares them with the authorization information of the principal.

(3) subject invokes authorization request

There are two ways for a subject to make an authorization request, one is programming, the other is annotated.

① programming: check roles through hasRole () of Subject, and check permissions through isPermitted ()

@ GetMapping ("/ dog") public String dog () {Subject subject = SecurityUtils.getSubject (); if (subject.hasRole ("dog")) {return "dog √";} else {return "dog ×";}} @ GetMapping ("/ cat") public String cat () {Subject subject = SecurityUtils.getSubject () If (subject.hasRole ("cat")) {return "cat √";} else {return "cat ×";}} @ GetMapping ("/ rap") public String rap () {Subject subject = SecurityUtils.getSubject (); if (subject.isPermitted ("rap")) {return "rap" } else {return "you don't have the authority to Rap the hammer!";}

The simulated user data are as follows:

/ * simulated database data * @ return * / private List getUsers () {List users = new ArrayList (2); List cat = new ArrayList (3); cat.add ("sing"); cat.add ("rap"); List dog = new ArrayList (3); dog.add ("jump"); dog.add ("basketball") Users.add (new User ("Zhang Xiaohei's cat", "123qwe", true, "cat", cat); users.add ("Zhang Xiaohei's dog", "123qwe", true, "dog", dog); return users;}

The test results are shown in the figure:

Authorization.gif

② annotated type:

First, you need to enable Aop annotations, and add the following methods to the ShiroConfig class:

/ * * enable aop annotation support * that is, use @ RequiresPermissions ("user/userList") * / @ Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor (SecurityManager securityManager) {AuthorizationAttributeSourceAdvisor attributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor () in controller; / / set the security manager attributeSourceAdvisor.setSecurityManager (securityManager); return attributeSourceAdvisor;} @ Bean @ ConditionalOnMissingBean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator () {DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator () DefaultAAP.setProxyTargetClass (true); return defaultAAP;}

For unauthorized users, a friendly prompt is required. A specific 403 page is generally returned, and the following method is added to the ShiroConfig class:

/ * handle unauthorized exceptions and return custom error page (403) * @ return * / @ Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver () {SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver (); Properties properties = new Properties (); / * unauthorized processing page * / properties.setProperty ("UnauthorizedException", "403.html"); resolver.setExceptionMappings (properties); return resolver;}

Explain the above code properties.setProperty ("UnauthorizedException", "403.html"); used to handle unauthorized exceptions crawled to UnauthorizedException and redirected to the 403.html page. We need to create a 403 page 403.html

403 is not authorized, you do not have access

Then check the roles and permissions in Controller using the annotations @ RequiresRoles ("xxx") and @ RequiresPermissions ("xxx")

@ GetMapping ("/ sing") @ RequiresRoles ("cat") public String sing () {return "sing";} @ GetMapping ("/ jump") @ RequiresPermissions ("jump") public String jump () {return "jump";}

The test results are shown in the figure:

Authorization2.gif

Summary: generally speaking, for unauthorized users who need to return to the specified 403 page, it is more convenient to use annotations; it is more convenient to do business logic (such as warning unauthorized request records), and to use programming.

(4) shiro tag at the front end

Usually, the front-end page display needs to be equivalent to the user's permissions, that is, only let the users see the content within their permissions. (for example, if the user "Zhang Xiaohei's cat" corresponds to the role "cat" and the corresponding permissions "sing" and "rap", then the user logs in and only displays the buttons of Cat, sing and rap)

There are usually two solutions:

One: after login, you can read the roles and permissions in the database, get the menu content that needs to be displayed, and render dynamically at the front end.

Second, all the content is written at the front end, and the rendering of the corresponding permission content part is controlled by the shiro tag in the front end.

Here is a demonstration of the use of shiro tags. (the front-end shiro tags include Jsp tags, Freemarker tags, Thymeleaf tags, etc., and thymeleaf tags are used in the demonstration.)

Shiro tag description: guest tag: ``. When the user does not have authentication, the corresponding information is displayed, that is, tourist access information. User tag: ``, the user has authenticated / remembers that the corresponding information will be displayed after I log in. Authenticated tag: ``, the user has been authenticated, that is, the Subject.login login is successful, not remembering that I logged in. NotAuthenticated tag: ``, the user has been authenticated, that is, the user has not called Subject.login to log in, including remembering that my automatic login is also unauthenticated. Principal tag: ``, equivalent to `((User) Subject.getPrincipals ()) .getUsername ()`. LacksPermission tag: ``. If the current Subject does not have permission, the body content will be displayed. HasRole tag: ``. If the current Subject has a role, the body content will be displayed. HasAnyRoles tag: ``, if the current Subject has any role (or relationship), the body content will be displayed. LacksRole tag: ``. If there is no role in the current Subject, the body content will be displayed. HasPermission tag: ``. If the current Subject has permission, the body content will be displayed.

Use:

① pom.xml introduces corresponding dependencies

Com.github.theborakompanioni thymeleaf-extras-shiro 2.0.0

Note: the version referenced here is 2.0.0. There was a compatibility problem before 1.0.2.

Add configuration to ② ShiroConfig

/ * use the shiro tag * @ return * / @ Bean public ShiroDialect shiroDialect () {return new ShiroDialect ();} for thymeleaf templates

③ front-end pages use shiro tags

DogCatSingJumpRapBasketball

Note: before use, shiro tag is introduced into the html tag, that is,

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

Internet Technology

Wechat

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

12
Report