如何为 RESTful 端点禁用基于 spring 表单的登录? [英] How can I disable spring form based login for RESTful endpoints?

查看:16
本文介绍了如何为 RESTful 端点禁用基于 spring 表单的登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据 auto-config='true' 使用基本和基于表单的身份验证配置了 spring-security.

I have spring-security configured using basic and form based authentication as per auto-config='true'.

我希望 /api/** 下的端点不使用基于表单的安全性./api/** 之外的其他端点应该使用基于表单的登录.我希望将 401 响应发送到这些未在 /api/** 下提供凭据的端点的任何调用.

I would like the endpoints under /api/** to NOT use form based security. Other endpoints outside of /api/** should use form based login. I would like a 401 response sent to any call for these endpoints who did not provide credentials under /api/**.

更新:感谢 Luke Taylor 在下面的评论,我想出了以下解决方案.

UPDATE: Thanks to Luke Taylor's comment below I have come up with the following solution.

注意:此技术只能从 spring-security 3.1 开始应用.

NOTE: This technique can only be applied as of spring-security 3.1.

首先我挑出/api/**.我们从不创建会话,但如果可用则使用会话,这是由 create-session="never"<session-management/> 的使用处理的.

First I single out /api/**. We never create a session though use one if available, this is handled by create-session="never" and the use of <session-management/>.

<http pattern="/api/**" create-session="never" use-expressions="true">
    <http-basic />
    <session-management />
    <intercept-url pattern="/api/**" access="hasRole('API_ACCESS')"/>
</http>

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
</http>

推荐答案

在 Spring Security 3.1 中,最好的选择是使用两个单独的 <http> 元素.然后可以将 Restful API 链配置为无状态并使用基本身份验证,而默认链可以使用正常的表单登录配置.

With Spring Security 3.1, your best option is to split the restful and non-restful parts of your application into separate filter chains by using two separate <http> elements. The restful API chain can then be configured to be stateless and use basic authentication, while the default chain can use a normal form-login configuration.

然后你会得到类似的东西:

You would then have something like:

<http pattern="/api/**" create-session="stateless">
    <intercept-url pattern="/api/**" access="ROLE_API_USER" />
    <http-basic />        
</http>

<!-- No pattern attribute, so defaults to matching any request -->
<http>
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login />        
</http>

链定义必须从最具体的模式到最一般的模式排序,因此默认链排在最后.

The chain definitions must be ordered from most specific pattern to most general, so the default chain comes last.

这篇关于如何为 RESTful 端点禁用基于 spring 表单的登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆