如何使用Spring Security for REST API对用户进行身份验证

Sha*_*yan 5 authentication rest spring-mvc spring-security

我一直在寻找这个问题的答案.但是,在阅读了包括Spring Security文档在内的大量资源之后,我仍然无法完全理解如何使用Spring Security对REST API的用户进行身份验证.
这是我想要做的:

  • 1)我想使用公钥 - 私钥实现像Amazon S3服务这样的身份验证
  • 2)为此,我将发送一个HMAC令牌,其中包含授权标头中的每个请求和公钥或我自己的自定义标头.
  • 3)我想使用spring security来实现令牌的服务器端处理,如下所示:
    • 1)从头部获取公钥.
    • 2)使用我的cutom UserDetailService类获取存储在数据库中的私钥
    • 3)使用请求和私钥计算服务器端的HMAC令牌,就像我在客户端上做的那样
    • 4)比较两个令牌以验证用户
    • 5)如果成功,则在SecurityContextHolder中存储认证对象.

从上面我不知道如何在Spring Security中执行此操作.我所理解的如下:

  • 1)使用<http>元素和自定义过滤器.我这样做了如下

    <http use-expressions="true" create-session="stateless" 
          authentication-manager-ref="restAuthenticationManager" 
          entry-point-ref="jkwebRestAuthenticationEntryPoint">
        <intercept-url pattern="/api/**" access="isAuthenticated()">
        </intercept-url>
        <custom-filter ref="jkWebSecurityHmacAuthenticationFilter"
         position="FORM_LOGIN_FILTER"/>
    </http>  
    
    Run Code Online (Sandbox Code Playgroud)
  • 2)现在我可以访问此过滤器中的标头并从中访问公钥.
    但是,我不知道如何使用此公钥从数据库中检索私钥.我是否需要使用自定义AuthenticationManager或AuthenticationProvider?以及如何做到这一点.我可以直接将我的UserDetailService Bean注入过滤器bean吗?

  • 3)如果我不需要使用自定义AuthenticationManager或AuthenticationProvider,我可以将UserDetailService直接注入过滤器bean,那么我是否需要自定义AuthenticationEntryPoint?
  • 4)假设我能够在过滤器中检索并进行身份验证,我是否需要调用chain.doFilter并将请求转发到相应的控制器?
  • 5)如果过滤器中的身份验证失败,我应该如何使用401响应客户端或自定义身份验证入口点?如果有,怎么样?
  • 6)我还需要将Authioities放在UserDetails中,我在UserDetailsS​​ervice实现中构造它并在UserDetails对象中设置它.只需在安全上下文中设置身份验证对象就可以完成工作,一旦身份验证成功,我们就会进行授权吗?

如果需要,我可以发布更多代码以便清晰.