1
我試圖使用JWT(Json Web Token)進行授權。在前端,我在後端Spring REST api上使用Angular2。我在後端添加了CORS過濾器。Angular2 JWT授權標題缺失在http響應中(添加了CORS支持)
在http請求中,我正在發送用戶名和密碼,並期待響應的'授權'標頭中有令牌。當我使用郵差時,一切正常,我收到包括'授權'的所有標題。另外,當我在Chrome控制檯中記錄流量時(通過表單進行用戶登錄時)「授權」標題出現在響應中,所以顯然它會返回到瀏覽器。但是,當我在我的角度的應用程序列表頭,有陣只有幾頭:
// auth.service.ts
login(username, password): Observable<boolean> {
// call remote service to authenticate user
return this.http.post(this.authUrl, JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
console.log("Authorization header: " + response.headers.get('Authorization'));
console.log("all headers: " + response.headers.keys());
// TODO - login successful if there's a jwt token in the response
});
}
那些2控制檯輸出的結果是:
Authorization header: null
all headers: Pragma,Cache-Control,Expires
下面是谷歌Chrome瀏覽器控制檯,您的屏幕截圖可以看到,所有需要的頭文件存在於客戶端:
服務器端的令牌生成(春季啓動):
public void addAuthentication(HttpServletResponse response, String username) throws UnsupportedEncodingException {
// Token generation
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, secret.getBytes("UTF-8"))
.compact();
response.addHeader(headerString, tokenPrefix + " " + JWT);
}
有沒有人有一些有用的建議?
感謝
SOLUTION:
public class CORSFilter implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
chain.doFilter(req, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
非常感謝隊友,這是解決方案! –
哇,謝謝! – menehune23