Token-based Authentication in Angular 6 with ASP.NET Core 2.1
Estimated study time: 14 minutes. Securing an Angular front end with a JWT-based ASP.NET Core backend.
Token-based authentication uses a signed token — typically a JWT (JSON Web Token) — instead of server-side sessions, to verify who a user is on every request. Here's how it fits together between an Angular 6 client and an ASP.NET Core 2.1 API.
How the Flow Works
- User submits credentials from the Angular login form.
- ASP.NET Core validates them and returns a signed JWT.
- Angular stores the token and attaches it to every subsequent API request.
- ASP.NET Core validates the token's signature and expiry on each request before processing it.
ASP.NET Core: Issuing the Token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config["Jwt:Secret"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
Expires = DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
Angular: Login and Store the Token
login(credentials: { username: string; password: string }) {
return this.http.post<{ token: string }>('/api/auth/login', credentials)
.pipe(tap(res => localStorage.setItem('token', res.token)));
}
Angular: Attaching the Token via an Interceptor
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('token');
if (token) {
req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next.handle(req);
}
}
ASP.NET Core: Validating the Token
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
💡 Tip: localStorage is convenient but readable by any script on the page. For anything security-sensitive, consider storing the token in a secure, httpOnly cookie managed by the ASP.NET Core backend instead.