![](/img/trans.png)
[英]Angular POST to Spring Security JWT login always returns Unauthorized
[英]Make Angular client login to Spring backend with JWT
我按照此指南將JWT添加到了我的Spring后端: https : //auth0.com/blog/securing-spring-boot-with-jwts/
當我使用Postman之類的軟件發送PUT請求時,一切正常,但是當我嘗試使用Angular客戶端登錄時, HttpServletRequest
的數據為空。
我通過以下方式在JWTLoginFilter
的attemptAuthentication
方法中檢查數據:
@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);
我的建議是我以錯誤的方式發送了請求正文,但我看不到我在做什么錯。
我試過了:
這些都沒有使任何數據出現在后端。
如果您需要有關任何內容的更多信息,請詢問我。
我知道了。
我還需要在我的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.