簡體   English   中英

使用JWT使Angular客戶端登錄到Spring后端

[英]Make Angular client login to Spring backend with JWT

我按照此指南將JWT添加到了我的Spring后端: https : //auth0.com/blog/securing-spring-boot-with-jwts/

當我使用Postman之類的軟件發送PUT請求時,一切正常,但是當我嘗試使用Angular客戶端登錄時, HttpServletRequest的數據為空。

我通過以下方式在JWTLoginFilterattemptAuthentication方法中檢查數據:

@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
        throws AuthenticationException, IOException, ServletException {
    String reqBody = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

    // this appears to be empty on angular client calls
    System.out.println(reqBody);

    ObjectMapper objectMapper = new ObjectMapper().configure(Feature.AUTO_CLOSE_SOURCE, true)
            .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    AccountCredentials creds = objectMapper.readValue(reqBody, AccountCredentials.class);

    return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(),
                creds.getPassword(), Collections.emptyList()));
}

我是這樣從客戶端發送請求的:

const user = {
  username: "asdf",
  password: "asdf"
};

// imported from '@angular/http'
const headers = new Headers({
  'Content-Type': 'application/json'
});
const body = JSON.stringify(user);
return this.http
  .put("http://localhost:8080/api/login", body, {headers})
  .toPromise()
  .then(response => response.json().data as User)
  .catch(this.handleError);

我的建議是我以錯誤的方式發送了請求正文,但我看不到我在做什么錯。

我試過了:

  • 將正文作為常規JS對象發送
  • 發送包裹在另一個對象中
  • 如示例所示,將其作為JSON字符串發送
  • 使用POST代替PUT(盡管它與Postman中的PUT一起使用)
  • 將Content-Type標頭更改為其他值

這些都沒有使任何數據出現在后端。

如果您需要有關任何內容的更多信息,請詢問我。

我知道了。

我還需要在我的HttpSecurity對象上允許CORS,如下所示:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors()
      .and()
      .so()
      .on();
  }
}

我不確定,為什么在不啟用HttpSecurity情況下啟用CORS的情況下接收到用Postman發送的請求,但是現在它可以正常工作了。

我希望以后可以幫助其他人。

這可能是原因,Spring OAuth 2通常期望使用URL編碼的用戶名和密碼進行POST請求。 所以嘗試這樣的事情。

return this.http.post(Url, "grant_type=password&username=" + username + "&password=" + password)

我不確定100%的情況是否是Spring-MVC ,但我希望它與我非常相似。

暫無
暫無

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

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