Grails安全插件自定义重定向

时间:2015-04-17 04:20:30

标签: grails spring-security

我是Groovy和Grails的新手。我使用数据库请求的请求映射使用Spring Security插件开发了一个应用程序。我希望根据角色自定义重定向到主页。

如果用户是ROLE_ADMIN,他将被重定向到他的主页视图adminUser / Homepage.gsp

如果用户是ROLE_USER,他将被重定向到他的主页视图User / Homepage.gsp

根据用户登录信息,我无法获得任何自定义身份验证重定向。

4 个答案:

答案 0 :(得分:1)

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import grails.plugin.springsecurity.SpringSecurityUtils

public class MyAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler 
{   
    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) 
    {
        def returnUrl = request.getSession().getAttribute('returnUrl')

        def roles = SpringSecurityUtils.getPrincipalAuthorities()

        for (String role in roles)
        {            
            if (role.equals("ROLE_ADMIN")) {
                returnUrl = '/AdminUser/index.gsp'
            }
            else if (role.equals("ROLE_USER")) {
                returnUrl = '/User/index.gsp'
            }
            else {
                returnUrl = '/'
            }
        }

        request.getSession().removeAttribute('returnUrl')

        return returnUrl
    }
}

这是我的工作代码.... 而是注入一个依赖项我使用SpringSecurityUtils获取当前用户角色并将其重定向到所需的页面...... 谢谢大家的支持。

@ sean3838谢谢你帮助我......

答案 1 :(得分:0)

我就是这样做的。我根据你的需要修改了它。如果有帮助,请告诉我。

在springsecurities中,在auth()方法下的LoginController执行类似这样的操作(在点击登录之前,它将获取用户所在的页面):

def auth() {

    session['returnUrl'] = request.getHeader("Referer")

    def config = SpringSecurityUtils.securityConfig

    if (springSecurityService.isLoggedIn()) {
        redirect uri: config.successHandler.defaultTargetUrl
        return
    }

    String view = 'auth'
    String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
    render view: view, model: [postUrl: postUrl,
                               rememberMeParameter: config.rememberMe.parameter]
}

现在在src / groovy里面创建一个auth成功处理程序:

package packageName

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class MyAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler 
{
    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) 
    {
        def returnUrl = request.getSession().getAttribute('returnUrl')

        // Get current users role using springSecurityService
        // You can inject springSecurityService into this class
        // http://stackoverflow.com/questions/6467167/how-to-get-current-user-role-with-spring-security-plugin

        if (role == 'ROLE_ADMIN')
        {
            returnUrl = '/adminUser/Homepage.gsp'
        }
        else if (role == 'ROLE_USER')
        {
            returnUrl = '/User/Homepage.gsp'
        }
        else
        {
            returnUrl = 'redirect somewhere'
        }

        request.getSession().removeAttribute('returnUrl')

        return returnUrl
    }
}

现在在conf / spring / resources.groovy下创建一个像这样的bean:

import grails.plugin.springsecurity.SpringSecurityUtils

// Place your Spring DSL code here
beans = {
    authenticationSuccessHandler(packageName.MyAuthSuccessHandler) {
        def conf = SpringSecurityUtils.securityConfig      
        requestCache = ref('requestCache')
        defaultTargetUrl = conf.successHandler.defaultTargetUrl
        alwaysUseDefaultTargetUrl = conf.successHandler.alwaysUseDefault
        targetUrlParameter = conf.successHandler.targetUrlParameter
        useReferer = conf.successHandler.useReferer
        redirectStrategy = ref('redirectStrategy')
    }
}

然后你应该好好去。如果有效,请告诉我。

答案 2 :(得分:0)

您必须在方法之前注入springSecurityService。此外,getAuthorities()应返回一个列表,因此您必须循环它(这是因为人们可以有多个角色)。

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class MyAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler 
{
    def springSecurityService

    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) 
    {
        def returnUrl = request.getSession().getAttribute('returnUrl')

        def roles = springSecurityService.getPrincipal().getAuthorities()

        for (role in roles)
        {
            if (role == 'ROLE_ADMIN')
            {
                returnUrl = '/adminUser/Homepage.gsp'
            }
            else if (role == 'ROLE_USER')
            {
                returnUrl = '/User/Homepage.gsp'
            }
        }

        request.getSession().removeAttribute('returnUrl')

        return returnUrl
    }
}

答案 3 :(得分:0)

假设你的BuildConfig中有这样的一行:

    compile ":spring-security-core:2.0-RC4"

以及BootStrap中的一些代码:

    def roleAdmin = new Role(authority:LSSRole.ROLE_ADMIN.toString()).save(failOnError: true)
    def roleFirm = new Role(authority:LSSRole.ROLE_FIRM.toString()).save(failOnError: true)
    def roleLaw = new Role(authority:LSSRole.ROLE_LAWYER.toString()).save(failOnError: true)
    def roleFin = new Role(authority:LSSRole.ROLE_FINANCE.toString()).save(failOnError: true)

使用此代码创建示例管理员用户:

    UserRole.create admin, roleAdmin, true

以及Config中的一些代码:

'/dbconsole/**':                     [LSSRole.ROLE_ADMIN.toString()],
'/secure/**':                        [LSSRole.ROLE_ADMIN.toString()],
'/payment/**':                       [LSSRole.ROLE_FIRM.toString()],
'/filing/**':                        [LSSRole.ROLE_FIRM.toString()],
'/finance/**':                       [LSSRole.ROLE_FINANCE.toString()],
'/lawyer/**':                        [LSSRole.ROLE_LAWYER.toString()],

其中LSSRole是枚举,有些代码如下:

        "/" {
            controller = "dispatch"
            action = "index"
        }

在您的UrlMappings中,用户在成功登录后转移用户,您可以构建这样的调度程序,根据用户的角色将用户分配到不同的目标网页:

class DispatchController {

def index() { 

    def controller = 'login'
    def action = 'auth'

    if (SpringSecurityUtils.ifAllGranted(LSSRole.ROLE_ADMIN.toString())) {
        controller = 'secure'
        action = 'index' 
    } else if (SpringSecurityUtils.ifAllGranted(LSSRole.ROLE_FINANCE.toString())) { 
        controller = 'finance'
        action = 'index' 
    } else if (SpringSecurityUtils.ifAllGranted(LSSRole.ROLE_FIRM.toString())) { 
        controller = 'filing'
        action = 'summary' 
    } else if (SpringSecurityUtils.ifAllGranted(LSSRole.ROLE_LAWYER.toString())) { 
        controller = 'lawyer'
        action = 'index' 
    } else {
        flash.message = 'Where do you think you\'re going? Nno no no'
        SecurityContextHolder.clearContext()
    }

    redirect controller:controller, action:action
}

希望这有帮助。