簡體   English   中英

Spring 安全 - 使用授權進行身份驗證 Header

[英]Spring Security - Authenticating with Authorization Header

我正在嘗試使用 Sprint 安全框架在 Spring 引導中為我的 HTTP 請求設置授權。 我是 Spring Security 的新手,我找不到任何適合我的案例的文檔。

我知道我們必須覆蓋 WebSecurityConfigurerAdapter 方法 - 配置(AuthenticationManagerBuilder)和配置(HttpSecurity)。 它適用於一些基本情況。 但是對於我正在從事的項目,我正在尋找一個特定的用例。

這是我正在嘗試設置的流程。 我的前端和后端托管在不同的域中,所以我也在尋找跨域授權。 通過發布到 REST API 登錄,[對於這個 API 單獨,應該沒有授權]

https://atlan.co/login - POST
{
'user_name': 'mani',
'password': 'mani'
}

/login REST Controller 收到用戶名和密碼,LDAP 是否進行身份驗證,一旦身份驗證成功,創建一個令牌並存儲在內存中的 DBRedis 用戶名 [最好映射到用戶令牌]。 並向瀏覽器發送登錄成功消息,並帶有 Set Authorization Cookie - Token。

之后,來自瀏覽器的每個請求都將附帶授權 header 和令牌值。

以上部分,我可以解決。 When the request comes in, I want to setup Spring Security so that it will read Authorization Header and get username, useremail from Redis in case if the token exists, pass the username, useremail to the Controller and the usual flow of the controller. 如果令牌不存在,則應以 JSON 格式拋出 401 UnAuthorized HTTP 錯誤以及自定義消息。

我已經嘗試閱讀 Stackoverflow、Spring 文檔中的問題,但我無法解決。 如果有人可以闡明這一點,那將非常有幫助。

您需要添加自定義 spring 過濾器來處理您的授權 header

public class YourAuthenticationFilter extends OncePerRequestFilter
{

  @Override
  protected void doFilterInternal(HttpServletRequest request,
    HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException
  {

    String xAuth = request.getHeader("Authorization");//here is your token value
    //Place here your redis checks, get Authentication and so on
    SecurityContextHolder.getContext().setAuthentication(auth);

    filterChain.doFilter(request, response);
  }

}

在您的安全配置中:

@Override
protected void configure(HttpSecurity http) throws Exception
{
  http
    //...
    .addFilterBefore(new YourAuthenticationFilter(), BasicAuthenticationFilter.class)
    //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM