Home > database >  How to use a property for group in Spring sec:authorize tag for hasAnyRole
How to use a property for group in Spring sec:authorize tag for hasAnyRole

Time:12-15

I'm attempting to use a property to specify group(s) to use in a jsp sec:authorize tag because the groups will be different depending on which region this app is deployed on. With the group name hard-coded, the following works:

<sec:authorize access="hasAnyRole('GRP_MY_GROUP_DEV')">

I was hoping I could do something along the lines of this (which doesn't work, it just behaves as if I'm not in the group):

<sec:authorize access="hasAnyRole(${allowed.groups.property})">

CodePudding user response:

You can create a @Bean and reference it.

@Component("authz")
public class JspAuthorizeAccess {
    @Value("${allowed.groups.property}")
    Set<String> allowedGroups;

    public boolean hasAnyRole(Authentication authentication) {
        var authorities = authentication.getAuthorities();
        var userGroups = AuthorityUtils.authorityListToSet(authorities);
        return !Collections.disjoint(allowedGroups, userGroups);
    } 
}
<sec:authorize access="@authz.hasAnyRole(authentication)">

CodePudding user response:

I ended up just Autowiring the groups property and adding it to the model in my controller:

@Value("${allowed.groups.property}")
private String adminGroups;
 ...
model.addAttribute("adminGroups", adminGroups);

then in the jsp I have:

<sec:authorize access="hasAnyRole('${adminGroups}')">

This does what I need, I was just wondering if I could do it more cleanly in just the jsp.

  • Related