Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

jwt - Web tokens in Angular 2+

I am sending a POST request to a back end REST API, via a login component. I get an x-auth token back in the response headers. How do I get and store this token so I can use it for all other API requests for the duration of the users logged in session? Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
localStorage.setItem('token', response.access_token);

This is how I did it with Angular 5:

My LoginService:

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 });
    }
}

My Login Component:

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);
                });
    }
}

I keep my token in localeStorage.

I have created interceptors for usage of this token:

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
};

This solution fro Angular 5 and HTTPClient. If you need solution for only Angular 2 let me know, I will post that to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...