Skip to content

Instantly share code, notes, and snippets.

@st3no
Created January 30, 2024 13:17
Show Gist options
  • Save st3no/42f757f1b3d374dd3e5656e2be8c116b to your computer and use it in GitHub Desktop.
Save st3no/42f757f1b3d374dd3e5656e2be8c116b to your computer and use it in GitHub Desktop.
interceptor
// auth.interceptor.ts
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
import { AuthService } from '../services/auth.service';
import { jwtDecode } from 'jwt-decode';
import { switchMap } from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
if (req.url.includes('login') || req.url.includes('refreshtoken')) {
return next(req);
}
var token = jwtDecode(authService.getAccessToken() ?? '');
if (new Date((token.exp ?? 0) * 1000) <= new Date()) {
return authService.refreshToken().pipe(
switchMap(() => {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${authService.getAccessToken()}`
}
});
return next(req);
})
);
} else {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${authService.getAccessToken()}`
}
});
return next(req);
}
};
// auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { jwtDecode } from "jwt-decode";
@Injectable({
providedIn: 'root'
})
export class AuthService {
private url = 'https://localhost:7000/identity';
constructor(private http: HttpClient) { }
login(username: string, password: string): Observable<any> {
const url = `${this.url}/login`;
this.http.post<any>(url, { username: username, password: password }).pipe(
catchError(err => {
console.error(err);
return of();
})
).subscribe(res => {
localStorage.setItem('access_token', res.access_token);
localStorage.setItem('refresh_token', res.refresh_token);
});
return of();
}
refreshToken(): Observable<any> {
const url = `${this.url}/refreshtoken`;
this.http.post<any>(
url,
{
AccessToken: localStorage.getItem('access_token'),
RefreshToken: localStorage.getItem('refresh_token')
}).pipe(
catchError(err => {
console.error(err);
return of();
})
).subscribe(res => {
localStorage.setItem('access_token', res.access_token);
localStorage.setItem('refresh_token', res.refresh_token);
});
return of();
}
logout(): void {
const url = `${this.url}/revoke/${this.getUsername()}`;
this.http.post<any>(url, {}).pipe(
catchError(err => {
console.error(err);
return of();
})
).subscribe(() => {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
});
}
getAccessToken(): string | null {
return localStorage.getItem('access_token');
}
getUsername(): string {
const token = this.getAccessToken();
return token
? jwtDecode<any>(token)['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']
: '';
}
getRole(): string {
const token = this.getAccessToken();
return token
? jwtDecode<any>(token)['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
: '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment