Grails安全实现

Grails安全实现,grails,Grails,我制作了以下控制器。 我可以登录和注销,但如何强制用户先登录? 我需要在登录时启动会话,并在注销时终止会话 class UserController { def scaffold = User def login = {} def authenticate = { def user = User.findByLoginAndPassword(params.login, params.password) if(user){ session

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

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的“安全注释”spring安全核心插件文档


选择1:

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

最流行的是“Spring安全核心插件”,它将强制用户在访问您的安全资源之前登录

参考链接:

选择2:

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
                }
            }
        }
    }
}
但是,如果您不想为您的应用程序使用任何外部插件(我建议使用一个),您可以利用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
                }
            }
        }
    }
}

参考链接:

我认为这会有所帮助。我认为您需要一种识别用户的方法,该方法可以纠正语法错误、严格的术语和固定的代码格式。
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
                }
            }
        }
    }
}