1

我正在使用 Spring Security Core Plugin 运行 Grails 应用程序。

当一个已经登录的用户试图访问一个页面而不访问它时,403总是调用在 UrlMappings.groovy 中配置的相同操作。

我一直在努力让我的应用程序根据拒绝访问的原因呈现不同的页面。例如:如果IS_AUTHENTICATED_FULLY需要,我想将用户重定向到他可以重新验证的表单。如果需要特定角色但不存在,我想将用户重定向到他可以请求该角色的页面。等等...

有谁知道如何存档?

==============================更新=================== ================

我试图通过文档onAuthorizationEven‌​t中描述的回调来解决问题。不幸的是,无论触发它的规则如何,事件参数总是相同的。

至少我可以访问被拒绝访问的 URI。有没有办法从 URI 获取安全规则,以便我可以比较当前用户的角色和状态并找出缺少的内容?那也许可以解决问题。

4

2 回答 2

2

在互联网上进行了长时间的研究后,终于让它与@yariash 的回复和这篇文章中的一些想法一起工作:

import org.springframework.context.ApplicationListener;
import org.springframework.security.access.event.AuthorizationFailureEvent
import org.springframework.security.authentication.RememberMeAuthenticationToken;

class AuthorizationFailureEventListener
        implements ApplicationListener<AuthorizationFailureEvent> {

    @Override
    public void onApplicationEvent(AuthorizationFailureEvent e) {
        def attributes = e.getConfigAttributes()

        if(!attributes) {
            return
        }

        def authentication = e.getAuthentication()
        def requiredAuthorities = attributes?.collect { it.getAttribute() }
        def userAuthorities = authentication.getAuthorities().collect { it.getAuthority() }
        def missingAuthorities = requiredAuthorities - userAuthorities

        if(requiredAuthorities.contains('IS_AUTHENTICATED_FULLY') &&
                !(authentication instanceof RememberMeAuthenticationToken)) {
            requiredAuthorities.remove('IS_AUTHENTICATED_FULLY')
        }

        e.getSource().getRequest().setAttribute("MISSING_AUTHORITIES", missingAuthorities);
    }

}

然后将此侦听器作为 bean 包含:

beans = {
    //...
    authorizationFailureEventListener(AuthorizationFailureEventListener) { bean ->
        bean.autowire = "byName"
    }
    //...
}

最后在我的错误控制器中:

static mappings = {
    //....
    "403"(controller:'error', action:'error403')
    //......
}

class ErrorController {  
    def error403() {
        def missingAuthorities = request.getAttribute("MISSING_AUTHORITIES")
        // Render the right view based on the missing authorities
    }
}
于 2016-08-16T20:12:23.440 回答
1

也许在那里创建控制器并访问异常?

static mappings = {
    //....
   "403"(controller:'error', action:'error403')
   //......
}


class ErrorController {  
   def error403() {
       def message = request.exception?.cause?.message; //access message and render right view
   }
}
于 2016-08-16T12:18:34.367 回答