3

我正在为我的 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不会导致错误 403,正如我预期的(或至少是预期的),而是继续提示输入用户名和密码。例如(其中编码的字符串是用户:用户):

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

当提供无法识别的用户凭据时,是否需要额外的配置来响应错误 403?我该怎么做呢?

4

2 回答 2

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 并被要求提供有效的登录/凭据。

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

于 2012-11-17T23:45:24.373 回答
1

您应该在 wget 或 curl 之类的客户端中尝试此操作。如果您被 401 拒绝,您的浏览器会多次为 Basic redentials 唠叨。这可能就是这种情况。

于 2012-11-17T23:41:47.940 回答