Angular 2+中的Web令牌

时间:2018-02-24 07:57:51

标签: angular jwt

我通过登录组件向后端REST API发送POST请求。我在响应头中返回一个x-auth令牌。 如何获取和存储此令牌,以便在用户登录会话期间将其用于所有其他API请求? 干杯

3 个答案:

答案 0 :(得分:2)

localStorage.setItem('token', response.access_token);

这就是我使用Angular 5的方式:

我的登录服务:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpParams } from '@angular/common/http';

import { HttpService } from '../services/http.service';

@Injectable()
export class LoginService{
    constructor(private _http: HttpService) {
    }

    login(user: string, pass: string) {
        const params = new HttpParams()
            .append('grant_type', 'password')
            .append('username', user)
            .append('password', pass);
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/x-www-form-urlencoded');
        return this._http.post('login', params, { headers: headers });
    }
}

我的登录组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { LoginService } from '../../services';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
    public pageTitle = 'User login';
    errorMessage = '';
    loginFormGroup: FormGroup;
    constructor(
        private fb: FormBuilder,
        private _loginService: LoginService) { }
    ngOnInit() {
        this.formBuild();
    }

    formBuild() {
        this.loginFormGroup = this.fb.group({
            loginUser: ['', [Validators.required]],
            loginPass: ['', [Validators.required]],
        });
    }

    onLogin() {
        let response: any;
        this._loginService.login(this.loginFormGroup.value.loginUser, this.loginFormGroup.value.loginPass)
            .subscribe(
                response => { response= response; },
                error => { this.errorMessage = <any>error; },
                () => {

                    localStorage.setItem('token', response.access_token);
                });
    }
}

我将我的令牌保存在localeStorage中。

我已经创建了使用此令牌的拦截器:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('token');
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
        return next.handle(request);
    }
}

export const TokenInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
};

此解决方案来自Angular 5和HTTPClient。如果你只需要Angular 2的解决方案让我知道,我会把它发给你。

答案 1 :(得分:1)

将您收到的令牌存储在Web浏览器的本地存储中,并使用http拦截器从所有响应中删除令牌,并将令牌添加到所有请求中。

答案 2 :(得分:1)

使用NgCookie模块,您可以设置如下:

  $cookies.put("token","your_response_val");

之后继续使用.... $cookies.get ()