Angular2登录服务JWT令牌 [英] Angular2 login service jwt token

查看:119
本文介绍了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...
}

这篇关于Angular2登录服务JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆