2012-12-28 42 views
2

我在STS 3.1中有一個Grails應用程序,並在UrlMappings.groovy和一組控制器中放置了一個REST API。我安裝了SpringSecurity的東西,所以我有登錄/註銷控制器和RegistrationCodeController等。我一直在使用瀏覽器界面登錄,但我需要從REST客戶端開始登錄。將REST身份驗證添加到Grails + SpringSecurity瀏覽器應用程序

什麼是我需要用來註冊/登錄/檢查登錄/註銷的具體URL和請求?

我已經能夠通過POST j_username和j_password登錄到/ j_spring_security_check。但是,如果我第一次發出認證失敗的請求,則發送到/ j_spring_security_check會自動返回初始失敗請求的結果。我需要一種登錄方式,在成功時總是返回成功/錯誤狀態和User.id。

回答

1

Config.groovy中,插入一些配置項:

grails.plugins.springsecurity.successHandler.alwaysUseDefault = true 
grails.plugins.springsecurity.successHandler.defaultTargetUrl = "/rest/success" 
grails.plugins.springsecurity.failureHandler.defaultFailureUrl = "/rest/failed" 

這將迫使登錄成功重定向到/ REST /成功。然後在此方法中,返回user.id:

import grails.converters.JSON 
class RestController { 

    def springSecurityService 

    def success() { 
     def response = ['status':'success', 'id':springSecurityService.currentUser.id] 
     render response as JSON 
    } 

    def failed() { 
     def response = ['status': 'failed'] 
     render response as JSON 
    } 
} 
+0

我可以看到爲什麼這應該起作用。不幸的是,當我第一次請求一個需要身份驗證的控制器時,我POST到/ j_spring_security_check,我仍然被重定向到第一個請求的響應。我是否應該通過其他請求登錄,而不是POST到/ j_spring_security_check? –

+0

我認爲發佈是很好的,因爲原始auth登錄表單具有相同的東西。它在網頁直接登錄場景中工作嗎? – coderLMN

+0

defaultTargetUrl重定向適用於網頁登錄,但不適用於來自我的休息客戶端的POST。 –

相關問題