Angular2登录服务JWT令牌
问题说明
我尝试用angular2前端实现jwt令牌. 当我尝试使用Postman的post方法接收令牌时,会收到授权令牌,但在Angular中这样做会返回空响应对象. 这是我使用的Angular服务的代码段.
I try to implement the jwt token with angular2 front-end. When I try receive the token with post method using Postman I receive authorization token but doing so in Angular returns null response object. Here's snippet code of Angular service I use.
return this.http.post(this.authUrl, { username: username, password: password })
.map((response: Response) => {
console.log(username ' ' password);
// login successful if there's a jwt token in the response
let token = response.json() && response.json().token;
console.log(token);
if (token) {
// set token property
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
});
问题是,当我尝试登录令牌时,令牌与响应相同. 对于代码的后端部分,我遵循了 jwt令牌的此实现.
The thing is that when I try to log the token is null same with response. For the back-end portion of code I followed this implementation of jwt token.
我唯一的线索就是尝试调用类似的post方法
The only clue I have is that trying to invoke post method like that
this.http.post<any>(this.authUrl, { username: username, password: password }).subscribe();
我收到订户对象.使用toPromise()而不是subscribe() 我得到了ZoneAwarePromise,但是在两种情况下都找不到令牌.
I receive Subscriber object. Doing so with toPromise() instead of subscribe() I got ZoneAwarePromise but I cannot locate token in both cases.
正确答案
当您从angular发送标题时,Api需要允许请求的来源.将此代码添加到Spring Boot控制器的类上方,如下所示.之后,将允许Api获取标头.
When you are sending headers from angular, Api needs to allow origins of requests. Add this code in Spring Boot controller above the class like below. After that Api will be allowed to get headers.
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class AuthenticationController {
//services...
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfjebi
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20