libs/auth/src/lib/basic-auth/basic-auth.service.ts
Maintains all basic auth tokens and also do the authentication process.
Properties |
|
Methods |
|
constructor(http: HttpClient)
|
||||||
Parameters :
|
Public auth |
auth(username: string, password: string, url: string)
|
Do the authentication.
Returns :
Observable<string>
|
Public clearToken | ||||||
clearToken(url: string)
|
||||||
Removes existing token.
Parameters :
Returns :
void
|
Public getToken | ||||||
getToken(url: string)
|
||||||
Gets the token for the given service url.
Parameters :
Returns :
string
|
Public hasToken | ||||||
hasToken(url: string)
|
||||||
Checks if a token exists.
Parameters :
Returns :
boolean
|
Private basicAuthTokens |
Type : Map<string | string>
|
Default value : new Map()
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
/**
* Maintains all basic auth tokens and also do the authentication process.
*/
@Injectable()
export class BasicAuthService {
private basicAuthTokens: Map<string, string> = new Map();
constructor(
private http: HttpClient
) { }
/**
* Do the authentication.
*/
public auth(username: string, password: string, url: string): Observable<string> {
const token = 'Basic ' + btoa(username + ':' + password);
const headers = new HttpHeaders({ 'Authorization': token });
return this.http.get(url, { headers })
.pipe(
map(res => {
this.basicAuthTokens.set(url, token);
return token;
})
);
}
/**
* Removes existing token.
*/
public clearToken(url: string): void {
if (this.basicAuthTokens.has(url)) {
this.basicAuthTokens.delete(url);
}
}
/**
* Checks if a token exists.
*/
public hasToken(url: string): boolean {
return this.basicAuthTokens.has(url);
}
/**
* Gets the token for the given service url.
*/
public getToken(url: string): string {
return this.basicAuthTokens.has(url) ? this.basicAuthTokens.get(url) : null;
}
}