Grails 3和Spring Security:当用户未登录时返回401

时间:2017-06-01 15:55:26

标签: authentication grails spring-security

在我的Grails 3.2.9网络应用程序中,我使用Spring Security插件来管理用户会话。这是依赖性:

compile "org.grails.plugins:spring-security-core:3.1.1"

应用程序的自然(长达数年)演变使所有控制器中的所有操作基本上都使用@Secured注释进行保护,以返回JSON,类似

return map as JSON    // grails.converters.JSON

这意味着所有操作基本上都像API一样。

但是,由于他们已经获得保护,当用户未被记录时,会对/login/auth(登录页面)执行重定向,这是您不会期望的。这就是我寻找返回401 unauthorized状态的方法而不是让Spring Security执行重定向的原因。

到目前为止,我已查看了pessimistic lockdown,并且通过网络搜索也引导我Spring Security Core REST plugin,但这两种方式似乎都不适应我的情况(对我而言)最后,但也许我错过了一些东西)。

所以欢迎任何建议,提前谢谢!

2 个答案:

答案 0 :(得分:0)

我没有Grails的经验,但也许您正在寻找的可以通过在Spring安全配置中提供org.springframework.security.web.AuthenticationEntryPoint的不同实现来实现。默认情况下,表单身份验证Spring使用org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint执行重定向到给定的登录页面。另一方面,org.springframework.security.web.authentication.HttpStatusEntryPoint只返回所需的状态。

在我们的项目入口点中,通过XML配置以旧式方式设置:

<http pattern="/**" auto-config="false" entry-point-ref="yourAuthenticationEntryPoint">

答案 1 :(得分:0)

resources.groovy

中注册以下内容

authenticationEntryPoint(Http401AuthenticationEntryPoint, 'Bearer')