Spring Security验证RESTful Web服务

Tyl*_*eat 3 authentication rest 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>
Run Code Online (Sandbox Code Playgroud)

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

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic YWRtaW46YWRtaW4=
Run Code Online (Sandbox Code Playgroud)

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

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
Run Code Online (Sandbox Code Playgroud)

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

GET /user/v1/Tyler HTTP/1.1
Authorization: Basic dXNlcjp1c2Vy
Run Code Online (Sandbox Code Playgroud)

当提供无法识别的用户凭据时,是否需要使用错误403进行响应的其他配置?我怎么能这样做呢?

Mac*_*rko 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());
Run Code Online (Sandbox Code Playgroud)

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

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