Created
October 18, 2017 19:57
-
-
Save tobecwb/9448f9fb20e0a4362a4290b7e34c3869 to your computer and use it in GitHub Desktop.
Angular 4 Authentication with REST API and JWT Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import * as jwt_decode from 'jwt-decode'; | |
import {isUndefined} from 'util'; | |
import {HttpClient, HttpErrorResponse, HttpHeaders, HttpResponseBase} from '@angular/common/http'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/Rx'; | |
export const TOKEN_NAME = 'jwt_token'; | |
const AUTH_HEADER_KEY = 'Authorization'; | |
const AUTH_PREFIX = 'Bearer'; | |
@Injectable() | |
export class AuthService { | |
private url = 'http://localhost:8080'; | |
private headers = new HttpHeaders({ 'Content-Type': 'application/json' }); | |
constructor(private http: HttpClient) { } | |
static getToken(): string { | |
return localStorage.getItem(TOKEN_NAME); | |
} | |
static setToken(token: string): void { | |
localStorage.setItem(TOKEN_NAME, token); | |
} | |
static getTokenExpirationDate(token?: string): Date { | |
if (!token) { | |
token = AuthService.getToken(); | |
} | |
const decoded = jwt_decode(token); | |
if (isUndefined(decoded.exp)) { | |
return null; | |
} | |
const date = new Date(0); | |
date.setUTCSeconds(decoded.exp); | |
return date; | |
} | |
static isTokenExpired(token?: string): boolean { | |
if (!token) { | |
token = AuthService.getToken(); | |
} | |
if (!token) { | |
return true; | |
} | |
const date = AuthService.getTokenExpirationDate(token); | |
if (isUndefined(date )) { | |
return false; | |
} | |
return !(date.valueOf() > new Date().valueOf()); | |
} | |
static logout() { | |
localStorage.removeItem(TOKEN_NAME); | |
} | |
static getAuthorizationHeader(): HttpHeaders { | |
// captura o token | |
const token = AuthService.getToken(); | |
if (isUndefined(token)) { | |
return null; | |
} | |
const authHeader = new HttpHeaders(); | |
authHeader.set(AUTH_HEADER_KEY, `${AUTH_PREFIX} ${token}`); | |
return authHeader; | |
} | |
private static processLoginResponse(res: HttpResponseBase): boolean { | |
if (res.headers.has(AUTH_HEADER_KEY)) { | |
const authorizationHeaderValue = res.headers.get(AUTH_HEADER_KEY); | |
const regex = new RegExp(`^${AUTH_PREFIX} (.*)`); | |
const m = regex.exec(authorizationHeaderValue); | |
if (m !== undefined && m.length === 2) { | |
AuthService.setToken(m[1]); | |
return true; | |
} | |
} | |
return false; | |
} | |
private static handleLoginError(error: HttpErrorResponse): boolean | Error { | |
if (error.status === 401) { | |
return false; | |
} else if (error.status === 400) { | |
// bad request | |
return new Error('Bad request'); | |
} else { | |
// erro geral | |
return new Error('Unknown error'); | |
} | |
} | |
login(usuario: string, senha: string): Promise<boolean> { | |
const credenciais = { | |
usuario: usuario, | |
senha: senha | |
}; | |
const req = this.http.post(`${this.url}/login`, credenciais, { headers: this.headers, observe: 'response' }); | |
return req.toPromise() | |
.then(r => AuthService.processLoginResponse(r)) | |
.catch((e) => { | |
const errorReturn = AuthService.handleLoginError(e); | |
if (errorReturn instanceof Error) { | |
return Promise.reject(errorReturn.message); | |
} else { | |
return e; | |
} | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
doLogin() { | |
const credenciais = { | |
usuario: 'john_smit', | |
senha: 'secret123' | |
}; | |
const reqAuth = this.authService.login(credenciais.usuario, credenciais.senha); | |
reqAuth.then(r => { | |
console.log('login:', r); | |
}).catch(e => { | |
console.error('error:', e); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment