First, create a new Angular project if you haven't already:
ng new angular-auth
cd angular-auth
ng add @angular/material # Optional for UI components
Install dependencies:
npm install @auth0/angular-jwt firebase @angular/fire
In auth.service.ts
, implement login and token handling:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://your-backend-api.com/auth'; // Replace with your API URL
constructor(private http: HttpClient) {}
login(credentials: { email: string; password: string }): Observable<any> {
return this.http.post(`${this.apiUrl}/login`, credentials);
}
logout() {
localStorage.removeItem('token');
}
getToken() {
return localStorage.getItem('token');
}
}
Modify app.module.ts
to use HTTP_INTERCEPTORS
:
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
],
})
export class AppModule {}
Create jwt.interceptor.ts
:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { AuthService } from './auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = this.authService.getToken();
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(req);
}
}
Add Firebase to your project and set up Firebase authentication. Modify environment.ts
:
export const environment = {
production: false,
firebase: {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID'
}
};
Create firebase-auth.service.ts
:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
@Injectable({
providedIn: 'root'
})
export class FirebaseAuthService {
constructor(private afAuth: AngularFireAuth) {}
async login(email: string, password: string) {
return this.afAuth.signInWithEmailAndPassword(email, password);
}
async logout() {
return this.afAuth.signOut();
}
getUser() {
return this.afAuth.authState;
}
}
Modify auth.guard.ts
to protect routes:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.getToken()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
Use it in app-routing.module.ts
:
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];
JWT and Firebase are powerful authentication solutions for Angular applications. JWT is ideal for self-managed authentication, while Firebase Auth is great for simplified authentication with Google, Facebook, and email logins. By implementing secure routes and authentication mechanisms, you can protect your application and improve user security. 🚀