为Grails + SpringSecurity浏览器应用添加REST认证



我在STS 3.1中有一个Grails应用程序,其REST API在UrlMappings中布局。Groovy和一组控制器。我安装了SpringSecurity的东西,所以我有登录/注销控制器和RegistrationCodeController等。我一直在使用浏览器界面登录,但我需要从一个REST客户端开始登录。

我需要使用哪些特定的url和请求来注册/登录/检查登录/注销?

我已经能够通过post j_username和j_password登录到/j_spring_security_check。但是,如果我首先发出一个身份验证失败的请求,那么post到/j_spring_security_check会自动返回初始的失败请求的结果。我需要一种方式登录,始终返回成功/错误状态和用户。Id on success.

在配置中。Groovy,插入一些配置项:

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

这将强制成功登录重定向到/rest/success。然后在这个方法中,返回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
    }
}

最新更新