2016-08-20 79 views
-1

我做了下面的控制器。 我可以登录和注销,但是如何强制用户先登录? 我需要在登录时启动一个会话并在注销时终止它。Grails安全实施

class UserController { 
    def scaffold = User 
    def login = {} 
    def authenticate = { 
     def user = User.findByLoginAndPassword(params.login, params.password) 
     if(user){ 
     session.user = user 
     flash.message = "Hello ${user.name}!" 
     redirect(controller:"entry", action:"list")  
     } else { 
     flash.message = "Sorry, ${params.login}. Please try again." 
     redirect(action:"login") 
     } 
    } 

    def logout = { 
     flash.message = "Goodbye ${session.user.name}" 
     session.user = null 
     redirect(controller:"entry", action:"list")  
    } 
} 
+0

我认为这将有助于。我想你想要一种识别登录用户的方式http://stackoverflow.com/questions/38688075/request-map-direct-me-to-login-page-in-grails/38793608#38793608 – Vahid

+0

纠正语法错误,收紧术语和固定代码格式。 – Prune

回答

1

选择1文件:

有许多可用于确保安全插件的数量你Grail的应用程序。

最流行的是“Spring Security Core Plugin”这将强制用户在访问您的安全资源之前登录。

参考链接:http://grails.org/plugin/spring-security-core

选择2:

但是,如果你不想使用任何外部插件,你的应用程序(我建议使用一个),你可以采取的优势“Filters” in Grail's

您可以在用户点击您的控制器的任何操作之前创建用于检查会话的过滤器,并且如果会话已过期/未创建,那么您可以将它们重定向到登录页面。

例子:

class SecurityFilterFilters { 

    def filters = { 
     loginCheck(controller: 'Your_controller_name(if many separate them with pipe(|))', action: "*") { 
      before = { 
       //check if user is logged in(if yes then there will be session.user) and action is not login action 
       if (!session.user && !actionName.equals('login')) { 
        //user is not logged in so redirect him to login page 
        redirect(controller: 'user', action: 'login') 
        return false 
       } 
      } 
     } 
    } 
} 

参考链接:http://docs.grails.org/2.2.1/ref/Plug-ins/filters.html