How Does a .NET Full Stack Developer Handle Authentication Using ASP.NET Core and Angular?
How Does a .NET Full Stack Developer Handle Authentication Using ASP.NET Core and Angular?
✅ Introduction
In modern web applications, authentication is essential for protecting user data and resources. A .NET full stack developer often builds secure login systems using:
ASP.NET Core (backend API)
Angular (frontend SPA)
JWT (JSON Web Token) for token-based authentication
Let’s walk through the complete process step by step.
🔐 Step 1: Set Up ASP.NET Core Authentication API
Create a new Web API project:
dotnet new webapi -n AuthDemoAPI
Add JWT support via NuGet:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Configure JWT authentication in Program.cs:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("yourSuperSecretKeyHere"))
};
});
Protect your API endpoint:
[Authorize]
[HttpGet("protected")]
public IActionResult GetSecret()
{
return Ok("This is a protected API response.");
}
👤 Step 2: Create Login Endpoint
Create a login DTO:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
In your controller:
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
if (login.Username == "admin" && login.Password == "pass123")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, login.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourSuperSecretKeyHere"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
return Unauthorized();
}
🌐 Step 3: Angular Frontend – Set Up Authentication Flow
Create Angular service for auth:
ng generate service auth
In auth.service.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
private apiUrl = 'https://localhost:5001/api';
constructor(private http: HttpClient) {}
login(userData: any) {
return this.http.post(`${this.apiUrl}/login`, userData);
}
storeToken(token: string) {
localStorage.setItem('authToken', token);
}
getToken() {
return localStorage.getItem('authToken');
}
logout() {
localStorage.removeItem('authToken');
}
isLoggedIn(): boolean {
return !!this.getToken();
}
}
🔁 Step 4: Attach JWT to Requests
Use HTTP Interceptor:
ng generate interceptor token
In token.interceptor.ts:
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = this.auth.getToken();
if (token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned);
}
return next.handle(req);
}
}
Add it to providers in app.module.ts:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
]
🔒 Step 5: Protect Angular Routes
Use route guards:
ng generate guard auth
Then in auth.guard.ts:
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 auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.auth.isLoggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
Apply guard in app-routing.module.ts:
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
🛡 Best Practices
Use HTTPS always
Use environment variables for secret keys
Set token expiration and refresh tokens
Hash passwords using bcrypt or Identity framework
Store JWT securely (e.g., HttpOnly cookies for better security)
✅ Summary
By combining ASP.NET Core and Angular, a .NET Full Stack Developer can:
Create secure login/logout flows
Authenticate users with JWT
Protect backend APIs and frontend routes
Manage user sessions effectively
Authentication isn’t just about logging in — it’s about trust, security, and user experience.
Learn Full Stack Dotnet Training Course
Read more
Comments
Post a Comment