开发者

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

开发者 https://www.devze.com 2022-12-20 16:40 出处:网络
I\'m currently developing a menu for my application that should be able to display only the c开发者_如何学编程ontrollers that the current user can access (requestmap defined in the database).

I'm currently developing a menu for my application that should be able to display only the c开发者_如何学编程ontrollers that the current user can access (requestmap defined in the database).

How can I check if the current user has access to a specific controller and action?


To check roles in view : Spring security plugin provides ifAllGranted, ifAnyGranted, ifNoneGranted etc., tags to check roles

For example, to check Admin Role of logged in User :

<sec:ifLoggedIn>
    <sec:ifAllGranted roles="ROLE_ADMIN">
        Admin resource
     </sec:ifAllGranted>
</sec:ifLoggedIn>

(tested in grails-2.2.2 and springSecurityCorePlugin-1.2.7.3)


org.grails.plugins.springsecurity.service.AuthenticateService authenticateService = new org.grails.plugins.springsecurity.service.AuthenticateService()
def isAdmin = authenticateService.ifAllGranted('ROLE_ADMIN')

if(isAdmin) {
   println 'I am Admin'
}


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()
    }
}


When dealing with permissions in views and taglibs, you can use the AuthorizeTagLib that's provided by the plugin.

For example, if you don't want a menu item to appear in your list for unauthenticated users, you might use:

<g:isLoggedIn>
  <li>Restricted Link</li>
</g:isLoggedIn>

If you have more specific roles defined and those roles are tied to your controller/action request mapping, you can use other tags, such as:

<g:ifAllGranted role="ROLE_ADMINISTRATOR">
  <li>Administrator Link</li>
</g:ifAllGranted>

In my experience, there's not yet a good way to tie the request mapping to your markup - I think you're going to have to use some of the above tags to limit access to content within a particular GSP.

I think that Burt Beckwith has a future modification (and is currently providing a beta version) to the plugin that integrates some ACL stuff that might solve this problem better in the future, but for now, I think the best approach is a hybrid request map + GSP tags one.


Not sure of the situation when this question was originally asked, but now you can check to see if a user is in a specific role by using SpringSecurityUtils.ifAllGranted() which takes a single String which is a comma delimited list of roles. It will return true if the current user belongs to all of them.

if(SpringSecurityUtils.ifAllGranted('ROLE_ADMIN,ROLE_USER')) {

Obviously, you can simply pass one role to the function if that is all you need. SpringSecurityUtils also has methods like ifAnyGranted, ifNotGranted, etc, so it should work for whatever it is you are trying to accomplish.

SpringSecurityUtils is a static API, so you don't need to create a private member named springSecurityUtils or anything like that.


You have to configure the file config/SecurityConfig.groovy (if it does not exists, create it, this overrides the default Security Configuration)

Add this entry:

requestMapString = """\
            CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
            PATTERN_TYPE_APACHE_ANT
            /=IS_AUTHENTICATED_REMEMBERED
            /login/auth=IS_AUTHENTICATED_ANONYMOUSLY
            /login/authajax=IS_AUTHENTICATED_ANONYMOUSLY
            /login/authfail=IS_AUTHENTICATED_ANONYMOUSLY 
            /js/**=IS_AUTHENTICATED_ANONYMOUSLY
            /css/**=IS_AUTHENTICATED_ANONYMOUSLY
            /images/**=IS_AUTHENTICATED_ANONYMOUSLY
            /plugins/**=IS_AUTHENTICATED_ANONYMOUSLY
            /**=IS_AUTHENTICATED_REMEMBERED
          """

This is means that you have to log in to enter the site. But all the resources (css, js, images, etc) is accessed without authentification.

If you want specific role only enter specific controller: For example, for UserController:

    /user/**=ROLE_ADMIN
    /role/**=ROLE_ADMIN 

For more information: http://www.grails.org/AcegiSecurity+Plugin+-+Securing+URLs

Regards


As far as I can tell, there doesn't look like there's an easy way to do it.

You can inject an instance of the grails AuthenticatedVetoableDecisionManager which is a concrete class of spring's AbstractAccessDecisionManager by doing this:

def accessDecisionManager

This has a "decide" method on it that takes 3 parameters

decide(Authentication authentication, Object object, ConfigAttributeDefinition config)

This is probably the method that you'd need to call and pass in the right things to figure out if the user with the auth creds can access that "object" (which looks like it's normally a request/response). Some additional digging around might prove out something workable here.

Short term, it's probably easier to use the ifAnyGranted taglib as another poster mentions.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号