Grails with SpringSecurity, check if the current user can access controller / action

前端 未结 8 2271
轮回少年
轮回少年 2021-02-15 13:57

I\'m currently developing a menu for my application that should be able to display only the controllers that the current user can access (requestmap defined in the database).

相关标签:
8条回答
  • 2021-02-15 14:21

    This question is pretty old, but I thought I'd post at least an answer that seems to work with Grails 2.0. If you are using the spring security plugin, there's a tag lib included called grails.plugins.springsecurity.SecurityTagLib.

    The tag-lib has a protected method, hasAccess() which can take the same params map that you give the g:link tag. So, if you extend SecurityTagLib, you can call hasAccess() and get the behavior you want. Why this isn't externalized into a service that can be injected is beyond me as the functionality seems to fulfill an obvious need.

    We use this to wrap the g:link tag and only generate a link of the user has access to the target page:

    def link = { attrs, body ->
        if( hasAccess(attrs.clone(), "link") ) {
            out << g.link(attrs, body)
        }
        else {
            out << body()
        }
    }
    
    0 讨论(0)
  • 2021-02-15 14:25

    I'm not sure about in Groovy, but in Java (so I assume Groovy too...) you could do (minus NPE checks):

    GrantedAuthority[] authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    boolean isAdmin = false;
    for(GrantedAuthority authority : authorities) {
        String role = authority.getAuthority();
        if(role != null && role.equals("ROLE_ADMIN")) {
            isAdmin = true;
            break;
        }
    }
    

    As for knowing whether or not the action is supported, you'd have to call the RequestMap service to get the roles for the mapping and see if it contains the found user role.

    0 讨论(0)
提交回复
热议问题