2016-08-20 89 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