• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Angular2登录服务JWT令牌

用户头像
it1352
帮助1

问题说明

我尝试用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.

正确答案

#1

当您从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
系列文章
更多 icon
同类精品
更多 icon
继续加载