add refresh token
This commit is contained in:
parent
5ab072992b
commit
f4c0bb0b76
@ -16,7 +16,8 @@ export class App {
|
|||||||
constructor(private authService: AuthService, private router: Router) {}
|
constructor(private authService: AuthService, private router: Router) {}
|
||||||
|
|
||||||
logout(): void {
|
logout(): void {
|
||||||
this.authService.logout();
|
this.authService.logout().subscribe(() => {
|
||||||
this.router.navigate(['/login']);
|
this.router.navigate(['/login']);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,36 +1,62 @@
|
|||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable, of } from 'rxjs';
|
||||||
import { tap } from 'rxjs/operators';
|
import { tap } from 'rxjs/operators';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
private readonly TOKEN_KEY = 'access_token';
|
private readonly ACCESS_TOKEN_KEY = 'accessToken';
|
||||||
|
private readonly REFRESH_TOKEN_KEY = 'refreshToken';
|
||||||
private apiUrl = 'http://localhost:4200/api/auth'; // Adjust if your server URL is different
|
private apiUrl = 'http://localhost:4200/api/auth'; // Adjust if your server URL is different
|
||||||
|
|
||||||
constructor(private http: HttpClient) {}
|
constructor(private http: HttpClient) {}
|
||||||
|
|
||||||
login(credentials: { username: string; password: string }): Observable<any> {
|
login(credentials: { username: string; password: string }): Observable<any> {
|
||||||
return this.http.post<{ access_token: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||||
tap((response) => this.setToken(response.access_token))
|
tap((response) => this.setTokens(response.accessToken, response.refreshToken))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
logout(): void {
|
logout(): Observable<any> {
|
||||||
localStorage.removeItem(this.TOKEN_KEY);
|
return this.http.post(`${this.apiUrl}/logout`, {}).pipe(
|
||||||
|
tap(() => this.removeTokens())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getToken(): string | null {
|
refreshToken(): Observable<any> {
|
||||||
return localStorage.getItem(this.TOKEN_KEY);
|
const refreshToken = this.getRefreshToken();
|
||||||
|
if (!refreshToken) {
|
||||||
|
return of(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {}, {
|
||||||
|
headers: { Authorization: `Bearer ${refreshToken}` }
|
||||||
|
}).pipe(
|
||||||
|
tap((response) => this.setTokens(response.accessToken, response.refreshToken))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getAccessToken(): string | null {
|
||||||
|
return localStorage.getItem(this.ACCESS_TOKEN_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
getRefreshToken(): string | null {
|
||||||
|
return localStorage.getItem(this.REFRESH_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
isLoggedIn(): boolean {
|
isLoggedIn(): boolean {
|
||||||
return this.getToken() !== null;
|
return this.getAccessToken() !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private setToken(token: string): void {
|
private setTokens(accessToken: string, refreshToken: string): void {
|
||||||
localStorage.setItem(this.TOKEN_KEY, token);
|
localStorage.setItem(this.ACCESS_TOKEN_KEY, accessToken);
|
||||||
|
localStorage.setItem(this.REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private removeTokens(): void {
|
||||||
|
localStorage.removeItem(this.ACCESS_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(this.REFRESH_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,26 +4,86 @@ import {
|
|||||||
HttpHandler,
|
HttpHandler,
|
||||||
HttpInterceptor,
|
HttpInterceptor,
|
||||||
HttpRequest,
|
HttpRequest,
|
||||||
|
HttpErrorResponse,
|
||||||
} from '@angular/common/http';
|
} from '@angular/common/http';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable, throwError, BehaviorSubject } from 'rxjs';
|
||||||
|
import { catchError, switchMap, filter, take } from 'rxjs/operators';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtInterceptor implements HttpInterceptor {
|
export class JwtInterceptor implements HttpInterceptor {
|
||||||
constructor(private authService: AuthService) {}
|
private isRefreshing = false;
|
||||||
|
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
|
||||||
|
|
||||||
|
constructor(private authService: AuthService, private router: Router) {}
|
||||||
|
|
||||||
intercept(
|
intercept(
|
||||||
request: HttpRequest<any>,
|
request: HttpRequest<any>,
|
||||||
next: HttpHandler
|
next: HttpHandler
|
||||||
): Observable<HttpEvent<any>> {
|
): Observable<HttpEvent<any>> {
|
||||||
const token = this.authService.getToken();
|
const accessToken = this.authService.getAccessToken();
|
||||||
if (token) {
|
|
||||||
request = request.clone({
|
if (accessToken) {
|
||||||
setHeaders: {
|
request = this.addToken(request, accessToken);
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
return next.handle(request);
|
|
||||||
|
return next.handle(request).pipe(
|
||||||
|
catchError((error) => {
|
||||||
|
if (error instanceof HttpErrorResponse && error.status === 401) {
|
||||||
|
return this.handle401Error(request, next);
|
||||||
|
} else {
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
|
||||||
|
if (!this.isRefreshing) {
|
||||||
|
this.isRefreshing = true;
|
||||||
|
|
||||||
|
// The subject is now single-use. Re-create it for each refresh cycle.
|
||||||
|
// The initial `null` value is what makes followers wait.
|
||||||
|
this.refreshTokenSubject = new BehaviorSubject<any>(null);
|
||||||
|
|
||||||
|
return this.authService.refreshToken().pipe(
|
||||||
|
switchMap((token: any) => {
|
||||||
|
this.isRefreshing = false;
|
||||||
|
this.refreshTokenSubject.next(token.accessToken);
|
||||||
|
return next.handle(this.addToken(request, token.accessToken));
|
||||||
|
}),
|
||||||
|
catchError((err) => {
|
||||||
|
this.isRefreshing = false;
|
||||||
|
|
||||||
|
// Propagate the error to all waiting followers and kill the subject.
|
||||||
|
this.refreshTokenSubject.error(err);
|
||||||
|
|
||||||
|
// Perform the logout and redirect
|
||||||
|
this.authService.logout().subscribe(() => {
|
||||||
|
this.router.navigate(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also ensure the original caller gets the error
|
||||||
|
return throwError(() => err);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return this.refreshTokenSubject.pipe(
|
||||||
|
filter((token) => token != null),
|
||||||
|
take(1),
|
||||||
|
switchMap((jwt) => {
|
||||||
|
return next.handle(this.addToken(request, jwt));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private addToken(request: HttpRequest<any>, token: string) {
|
||||||
|
return request.clone({
|
||||||
|
setHeaders: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,16 @@
|
|||||||
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
|
import {
|
||||||
import { AuthService } from './auth.service';
|
Controller,
|
||||||
|
Post,
|
||||||
|
Body,
|
||||||
|
ValidationPipe,
|
||||||
|
UseGuards,
|
||||||
|
Req,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import AuthService from './auth.service';
|
||||||
import { LoginRequestDto } from './dto/login-request.dto';
|
import { LoginRequestDto } from './dto/login-request.dto';
|
||||||
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
import { JwtRefreshAuthGuard } from './jwt-refresh-auth.guard';
|
||||||
|
import express from 'express';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@ -10,4 +20,18 @@ export class AuthController {
|
|||||||
async login(@Body(new ValidationPipe()) body: LoginRequestDto) {
|
async login(@Body(new ValidationPipe()) body: LoginRequestDto) {
|
||||||
return await this.authService.login(body);
|
return await this.authService.login(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post('logout')
|
||||||
|
async logout(@Req() req: express.Request) {
|
||||||
|
const user = req.user as { sub: number };
|
||||||
|
return await this.authService.logout(user.sub);
|
||||||
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtRefreshAuthGuard)
|
||||||
|
@Post('refresh')
|
||||||
|
async refresh(@Req() req: express.Request) {
|
||||||
|
const user = req.user as { sub: number; refreshToken: string };
|
||||||
|
return await this.authService.refreshToken(user.sub, user.refreshToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,14 +2,15 @@ import { Module } from '@nestjs/common';
|
|||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
import { UserModule } from '../user/user.module';
|
import { UserModule } from '../user/user.module';
|
||||||
import { AuthService } from './auth.service';
|
import AuthService from './auth.service';
|
||||||
import { AuthController } from './auth.controller';
|
import { AuthController } from './auth.controller';
|
||||||
import { JwtStrategy } from './jwt.strategy';
|
import { JwtStrategy } from './jwt.strategy';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtRefreshTokenStrategy } from './jwt-refresh.strategy';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule, // <--- Import ConfigModule here
|
ConfigModule,
|
||||||
UserModule,
|
UserModule,
|
||||||
PassportModule,
|
PassportModule,
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
@ -17,11 +18,11 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
|
|||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
useFactory: (configService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
secret: configService.get<string>('JWT_SECRET'),
|
secret: configService.get<string>('JWT_SECRET'),
|
||||||
signOptions: { expiresIn: '60m' },
|
signOptions: { expiresIn: '2m' },
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providers: [AuthService, JwtStrategy],
|
providers: [AuthService, JwtStrategy, JwtRefreshTokenStrategy],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
})
|
})
|
||||||
export class AuthModule {}
|
export class AuthModule {}
|
||||||
|
|||||||
@ -4,12 +4,15 @@ import { JwtService } from '@nestjs/jwt';
|
|||||||
import * as bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
import { User } from '../entity/user';
|
import { User } from '../entity/user';
|
||||||
import { LoginRequest, LoginResponse } from '../types';
|
import { LoginRequest, LoginResponse } from '../types';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import type { StringValue } from 'ms';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
class AuthService {
|
||||||
constructor(
|
constructor(
|
||||||
private userService: UserService,
|
private userService: UserService,
|
||||||
private jwtService: JwtService,
|
private jwtService: JwtService,
|
||||||
|
private configService: ConfigService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async validateUser(username: string, pass: string): Promise<User | null> {
|
async validateUser(username: string, pass: string): Promise<User | null> {
|
||||||
@ -34,19 +37,77 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tokens = await this.getTokens(user);
|
||||||
|
await this.userService.setRefreshToken(user.id, tokens.refreshToken);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
async logout(userId: number): Promise<void> {
|
||||||
|
await this.userService.setRefreshToken(userId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshToken(
|
||||||
|
userId: number,
|
||||||
|
refreshToken: string,
|
||||||
|
): Promise<LoginResponse> {
|
||||||
|
const user = await this.userService.findOne(userId);
|
||||||
|
if (!user || !user.hashedRefreshToken) {
|
||||||
|
throw new UnauthorizedException('Access Denied');
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshTokenMatches = await bcrypt.compare(
|
||||||
|
refreshToken,
|
||||||
|
user.hashedRefreshToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!refreshTokenMatches) {
|
||||||
|
throw new UnauthorizedException('Access Denied');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = await this.getTokens(user);
|
||||||
|
await this.userService.setRefreshToken(user.id, tokens.refreshToken);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getTokens(user: User): Promise<LoginResponse> {
|
||||||
const roles: Set<string> = new Set<string>();
|
const roles: Set<string> = new Set<string>();
|
||||||
for (const group of user.groups ?? []) {
|
for (const group of user.groups ?? []) {
|
||||||
for (const role of group.roles ?? []) {
|
for (const role of group.roles ?? []) {
|
||||||
roles.add(role.name);
|
roles.add(role.name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const payload = {
|
|
||||||
username: user.username,
|
// let accessToken: string, refreshToken: string;
|
||||||
sub: user.id,
|
const [accessToken, refreshToken] = await Promise.all([
|
||||||
roles: Array.from(roles),
|
this.jwtService.signAsync(
|
||||||
};
|
{
|
||||||
|
username: user.username,
|
||||||
|
sub: user.id,
|
||||||
|
roles: Array.from(roles),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
secret: this.configService.get<string>('JWT_SECRET'),
|
||||||
|
expiresIn: this.configService.get<StringValue>('JWT_EXPIRATION_TIME'),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
this.jwtService.signAsync(
|
||||||
|
{
|
||||||
|
sub: user.id,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
|
||||||
|
expiresIn: this.configService.get<StringValue>(
|
||||||
|
'JWT_REFRESH_EXPIRATION_TIME',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
access_token: this.jwtService.sign(payload),
|
accessToken,
|
||||||
|
refreshToken,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default AuthService;
|
||||||
|
|||||||
5
server/src/auth/jwt-refresh-auth.guard.ts
Normal file
5
server/src/auth/jwt-refresh-auth.guard.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtRefreshAuthGuard extends AuthGuard('jwt-refresh') {}
|
||||||
47
server/src/auth/jwt-refresh.strategy.ts
Normal file
47
server/src/auth/jwt-refresh.strategy.ts
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { ExtractJwt, Strategy, StrategyOptionsWithRequest } from 'passport-jwt';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
// Define the shape of the JWT payload
|
||||||
|
interface JwtPayload {
|
||||||
|
sub: number;
|
||||||
|
// iat and exp are automatically added by passport-jwt
|
||||||
|
iat: number;
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define the shape of the object returned by the validate function
|
||||||
|
interface JwtPayloadWithRefreshToken extends JwtPayload {
|
||||||
|
refreshToken: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtRefreshTokenStrategy extends PassportStrategy(
|
||||||
|
Strategy,
|
||||||
|
'jwt-refresh',
|
||||||
|
) {
|
||||||
|
constructor(private configService: ConfigService) {
|
||||||
|
super({
|
||||||
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
|
secretOrKey: configService.get<string>('JWT_REFRESH_SECRET'),
|
||||||
|
passReqToCallback: true,
|
||||||
|
} as StrategyOptionsWithRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
validate(req: Request, payload: JwtPayload): JwtPayloadWithRefreshToken {
|
||||||
|
const refreshToken = req.get('Authorization')?.replace('Bearer', '').trim();
|
||||||
|
|
||||||
|
// Ensure refreshToken is not undefined before returning
|
||||||
|
if (!refreshToken) {
|
||||||
|
// This case should be rare given the guard is used, but it's good practice
|
||||||
|
// to handle it. Depending on strictness, you might throw an error.
|
||||||
|
// For now, we'll proceed, but in a real-world scenario, logging or an error
|
||||||
|
// might be better.
|
||||||
|
return { ...payload, refreshToken: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...payload, refreshToken };
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -24,4 +24,7 @@ export class User {
|
|||||||
@ManyToMany(() => UserGroup)
|
@ManyToMany(() => UserGroup)
|
||||||
@JoinTable()
|
@JoinTable()
|
||||||
groups: UserGroup[];
|
groups: UserGroup[];
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
hashedRefreshToken?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,14 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddRefreshTokenToUserObject1763106308120 implements MigrationInterface {
|
||||||
|
name = 'AddRefreshTokenToUserObject1763106308120'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "user" ADD "hashedRefreshToken" character varying`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "hashedRefreshToken"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -4,8 +4,7 @@ export interface LoginRequest{
|
|||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoginResponse{
|
export interface LoginResponse {
|
||||||
access_token: string;
|
accessToken: string;
|
||||||
|
refreshToken: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -54,4 +54,20 @@ export class UserService {
|
|||||||
this.logger.log(`Removing user with id: ${id}`, 'UserService');
|
this.logger.log(`Removing user with id: ${id}`, 'UserService');
|
||||||
await this.usersRepository.delete(id);
|
await this.usersRepository.delete(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async setRefreshToken(
|
||||||
|
id: number,
|
||||||
|
refreshToken: string | null,
|
||||||
|
): Promise<void> {
|
||||||
|
this.logger.log(
|
||||||
|
`Updating refresh token for user with id: ${id}`,
|
||||||
|
'UserService',
|
||||||
|
);
|
||||||
|
if (refreshToken) {
|
||||||
|
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
|
||||||
|
await this.usersRepository.update(id, { hashedRefreshToken });
|
||||||
|
} else {
|
||||||
|
await this.usersRepository.update(id, { hashedRefreshToken: undefined });
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user