Sunday, April 13, 2025

Build a Secure Login System with .NET Core + Angular

 Creating a secure login system with .NET Core (Backend) and Angular (Frontend) involves implementing industry best practices for authentication, such as JWT (JSON Web Tokens), password hashing, and role-based access control.

Here's a high-level breakdown of what to implement:

🔐 Backend (.NET Core) – Secure API with JWT

Tools/Packages:

  • .NET 7 or later

  • Microsoft.AspNetCore.Authentication.JwtBearer

  • EntityFrameworkCore

  • AutoMapper

  • FluentValidation (optional for DTO validation)

✅ Backend Features

  1. User Registration

    • Hash passwords using PasswordHasher<TUser>

    • Store user info in a SQL database (e.g., SQL Server)

  2. Login & JWT Generation

    • Authenticate credentials

    • Return JWT token on successful login

  3. Secure Endpoints

    • Use [Authorize] attribute

    • Role-based authorization via claims

  4. Token Validation

    • Middleware to validate JWT tokens in headers

  5. Refresh Token (Optional for extra security)


🔧 Sample .NET Code (Key Snippets)

Startup.cs / Program.cs (Service Config)

csharp

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = config["Jwt:Issuer"], ValidAudience = config["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"])) }; });

Generate JWT Token

csharp

public string GenerateToken(ApplicationUser user) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var creds = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])), SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); }

🌐 Frontend (Angular) – Login UI + Token Handling

✅ Angular Features

  1. Login Form with Angular Reactive Forms

  2. AuthService to manage token-based login

  3. Http Interceptor to append JWT token to HTTP requests

  4. Route Guards to restrict access to secure routes


🔧 Angular Key Snippets

AuthService.ts

ts

login(credentials: any): Observable<any> { return this.http.post('https://your-api-url/api/auth/login', credentials) .pipe(tap((res: any) => { localStorage.setItem('token', res.token); })); } isLoggedIn(): boolean { return !!localStorage.getItem('token'); }

Auth Interceptor

ts

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token'); if (token) { req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(req); }

Route Guard

ts

canActivate(): boolean { return this.authService.isLoggedIn(); }

No comments:

Post a Comment