In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "Spring Security rights management voting device and voting mechanism how to achieve", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Spring Security rights management voting device and voting mechanism how to achieve" it!
1. Voting apparatus
Let's take a look at the voting device first.
In Spring Security, the voter is specified by the AccessDecisionVoter interface. Let's take a look at the implementation of the AccessDecisionVoter interface:
As you can see, there are many implementations of voter. We can choose one or more of them, or we can customize the voter. The default voter is WebExpressionVoter.
Let's look at the definition of AccessDecisionVoter:
Public interface AccessDecisionVoter {int ACCESS_GRANTED = 1; int ACCESS_ABSTAIN = 0; int ACCESS_DENIED =-1; boolean supports (ConfigAttribute attribute); boolean supports (Class clazz); int vote (Authentication authentication, S object, Collection attributes);}
Let me explain a little bit:
First of all, three constants are defined, and you can see the meaning of each constant from the constant name. 1 indicates approval, 0 indicates abstention, and-1 indicates rejection.
Two supports methods are used to determine whether the voter supports the current request.
Vote is the specific voting method. Implemented in different implementation classes. With three parameters, authentication represents the current login principal; object is an ilterInvocation that encapsulates the current request; and attributes represents the collection of roles required by the currently accessed interface.
Let's take a look at the implementation of several voting devices.
1.1 RoleVoter
RoleVoter is mainly used to determine whether the current request has the required role for this API. Let's take a look at its vote method:
Public int vote (Authentication authentication, Object object, Collection attributes) {if (authentication = = null) {return ACCESS_DENIED;} int result = ACCESS_ABSTAIN; Collection authorities = extractAuthorities (authentication); for (ConfigAttribute attribute: attributes) {if (this.supports (attribute)) {result = ACCESS_DENIED For (GrantedAuthority authority: authorities) {if (attribute.getAttribute () .equals (authority.getAuthority () {return ACCESS_GRANTED;}} return result }
The judgment logic of this method is very simple. If the current login principal is null, return ACCESS_DENIED directly to deny access; otherwise, extract the role information from the current login principal authentication and compare it with attributes. If you have any of the required roles in attributes, return ACCESS_GRANTED means access is allowed. For example, the role in attributes is [a _ r _ b _ p _ c]. If the current user has a, then access is allowed, and it is not necessary to have all three roles at the same time.
Another thing to note is the supports method of RoleVoter. Let's take a look at:
Public class RoleVoter implements AccessDecisionVoter {private String rolePrefix = "ROLE_"; public String getRolePrefix () {return rolePrefix;} public void setRolePrefix (String rolePrefix) {this.rolePrefix = rolePrefix } public boolean supports (ConfigAttribute attribute) {if ((attribute.getAttribute ()! = null) & & attribute.getAttribute () .startsWith (getRolePrefix () {return true;} else {return false }} public boolean supports (Class clazz) {return true;}}
As you can see, a rolePrefix prefix is involved here, which is ROLE_, in the supports method. Only the supoorts method whose principal role prefix is ROLE_, will return true, and this voter will take effect.
1.2 RoleHierarchyVoter
RoleHierarchyVoter is a subclass of RoleVoter. On the basis of RoleVoter role judgment, role hierarchical management, that is, role inheritance, is introduced. About role inheritance, friends can refer to Song GE's previous article (how to make superiors have all the permissions of subordinates in Spring Security? ).
The vote method of the RoleHierarchyVoter class is the same as RoleVoter, except that the RoleHierarchyVoter class overrides the extractAuthorities method.
@ OverrideCollection extractAuthorities (Authentication authentication) {return roleHierarchy.getReachableGrantedAuthorities (authentication .getAuthences ());}
After the role layering, you need to obtain the actual roles through the getReachableGrantedAuthorities method.
1.3 WebExpressionVoter
This is a voter based on expression permission control. Brother Song will spend some time talking to his friends about expression-based permission control. Here, let's take a look at its vote method without doing too much:
Public int vote (Authentication authentication, FilterInvocation fi, Collection attributes) {assert authentication! = null; assert fi! = null; assert attributes! = null; WebExpressionConfigAttribute weca = findConfigAttribute (attributes); if (weca = = null) {return ACCESS_ABSTAIN;} EvaluationContext ctx = expressionHandler.createEvaluationContext (authentication, fi) Ctx = weca.postProcess (ctx, fi); return ExpressionUtils.evaluateAsBoolean (weca.getAuthorize_Expression (), ctx)? ACCESS_GRANTED: ACCESS_DENIED;}
The code here actually builds the weca object based on the incoming attributes attribute, then builds the ctx object based on the passed authentication parameters, and finally calls the evaluateAsBoolean method to determine whether the permissions match.
The above introduction of these three voting devices is the three we use more in the actual development.
1.4 other
In addition, there are several unpopular voting devices, Brother Song also said a little bit, friends to understand.
Jsr250Voter
Voter that handles Jsr-250 permission annotations, such as @ PermitAll,@DenyAll, etc.
AuthenticatedVoter
AuthenticatedVoter is used to determine whether there are IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED and IS_AUTHENTICATED_ANONYMOUSLY roles on the ConfigAttribute.
IS_AUTHENTICATED_FULLY indicates that the current authenticated user must be authenticated by user name / password, but the authentication by RememberMe is invalid.
IS_AUTHENTICATED_REMEMBERED indicates that the currently logged-in user must be authenticated through RememberMe.
IS_AUTHENTICATED_ANONYMOUSLY indicates that the currently logged in user must be an anonymous user.
Consider this voter when the project introduces RememberMe and wants to distinguish between different authentication methods.
AbstractAclVoter
Provides help methods for writing domain object ACL options that are not bound to any particular ACL system.
PreInvocationAuthorizationAdviceVoter
Use the permissions of @ PreFilter and @ PreAuthorize annotation processing to authorize through PreInvocationAuthorizationAdvice.
Of course, if these voting devices can not meet the needs, they can also be customized.
two。 Voting mechanism
There may not be only one voter for a request, but there may also be multiple voter, so we need a voting mechanism on the basis of the voter.
There are three main categories related to voting:
AffirmativeBased
ConsensusBased
UnanimousBased
Their inheritance relationship is shown above.
All three decision makers call all the voter in the project, and the default decision maker is AffirmativeBased.
The differences between the three decision makers are as follows:
AffirmativeBased: if a voting machine agrees, it will be passed.
ConsensusBased: most voting instruments agree to pass. If there is a draw, it depends on the value of the allowIfEqualGrantedDeniedDecisions parameter.
UnanimousBased all voting devices agree before the request is approved.
The specific judgment logic here is relatively simple, Song Brother will not post the source code, interested friends can see for themselves.
3. Where is the configuration?
When we use expression-based permission control, it looks like this:
Http.authorizeRequests () .antMatching ("/ admin/**"). HasRole ("admin") .antMatrices ("/ user/**"). HasRole ("user") .anyRequest () .fullyAuthenticated ()
Then the default voter and decision maker are configured in the AbstractInterceptUrlConfigurer#createDefaultAccessDecisionManager method:
Private AccessDecisionManager createDefaultAccessDecisionManager (H http) {AffirmativeBased result = new AffirmativeBased (getDecisionVoters (http)); return postProcess (result);} List > decisionVoters = new ArrayList (); WebExpressionVoter expressionVoter = new WebExpressionVoter (); expressionVoter.setExpressionHandler (getExpressionHandler (http)); decisionVoters.add (expressionVoter); return decisionVoters;}
Here you can see the default decision maker and voter, and after the decision maker AffirmativeBased object is created, it also calls the postProcess method to register in the Spring container. Combined with the previous articles in this series, you know that it is very easy to modify the object if we want to:
Http.authorizeRequests () .antMatrices ("/ admin/**"). HasRole ("admin") .antMatrices ("/ user/**"). HasRole ("user") .anyRequest (). FullyAuthenticated (). WithObjectPostProcessor (new ObjectPostProcessor () {@ Override public O postProcess (O object) {List)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.