Spring Security验证RESTful Web服务

时间:2012-11-17 23:15:58

标签: rest authentication spring-mvc spring-security

我正在努力为我的RESTful Web服务添加基本身份验证(使用Spring MVC实现),Spring Security从未真正使用过它。现在我只是使用内存中UserService,目的是稍后添加基于存储库的内容。

<security:http>
    <security:http-basic />
    <security:intercept-url pattern="/**" access="ROLE_ADMIN" />
</security:http>

<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="admin" password="admin"
                authorities="ROLE_USER, ROLE_ADMIN" />
            <security:user name="guest" password="guest"
                authorities="ROLE_GUEST" />
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>

这很好用,即发送以下请求授予我访问所需资源的权限(编码字符串为admin:admin):

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic YWRtaW46YWRtaW4=

发送以下请求会给我一个错误403(其中编码的字符串是guest:guest):

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=

但是,发送UserService中包含 not 所提供的用户名的请求不会导致错误403,如我所料(或至少需要),而是继续提示用户名和密码。例如。 (编码字符串是user:user):

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic dXNlcjp1c2Vy

如果提供了无法识别的用户凭据,是否需要使用错误403进行响应?我怎么能这样做?

2 个答案:

答案 0 :(得分:6)

首先,

当用户已经过身份验证但无权执行特定操作时,应使用

403 Forbidden。在您的示例中,guest已成功通过身份验证,但未获得查看页面的权限,因为他只是来宾。

您应该使用401 Unauthorized表示您的用户未成功通过身份验证。

有关HTTP错误代码的更多信息:http://en.wikipedia.org/wiki/HTTP_401#4xx_Client_Error

其次,

您可以通过扩展BasicAuthenticationFilter来指定自定义行为。 有protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse AuthenticationException failed)方法可以覆盖并做任何适当的事情。在默认实现中,该方法为空。

关于注入自定义过滤器的Spring Security文档:CLICK

编辑:

每次您的身份验证输入无效时,Spring Security会执行哪些操作:

public class BasicAuthenticationEntryPoint implements AuthenticationEntryPoint {
...
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

response.addHeader("WWW-Authenticate", "Basic realm=\"" + realmName + "\"");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

因此,默认行为是正确的。用户被发送401并被要求提供有效的登录/凭证。

在覆盖之前,尝试了解默认行为。源代码:CLICK

答案 1 :(得分:1)

你应该在像wget或curl这样的客户端中尝试这个。如果你的401被拒绝,你的浏览器会为你的基本订阅几次唠叨。这可能就是这种情况。