【问题标题】:Grails security implementationGrails 安全实现
【发布时间】:2016-10-23 22:07:03
【问题描述】:

我制作了以下控制器。 我可以登录和注销,但是如何强制用户先登录? 我需要在登录时启动会话并在注销时终止它。

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

【问题讨论】:

标签: grails


【解决方案1】:

选择 1:

有许多安全插件可用于保护 Grail 的应用程序。

最受欢迎的是“Spring Security Core Plugin”,它会强制用户在访问您的安全资源之前登录。

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

选择 2:

但如果您不想为您的应用程序使用任何外部插件(我建议使用一个),您可以利用 Grail 中的 "Filters"

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

示例:

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

【讨论】:

    【解决方案2】:

    请参阅 Grails 的“安全注释”spring-security-core 插件文档

    https://grails-plugins.github.io/grails-spring-security-core/v3/

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 1970-01-01
      • 2012-11-20
      • 2017-08-06
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2020-07-01
      相关资源
      最近更新 更多