Prompt Title: JWT token

Created 1 year ago
Votes 0
Views 183 times
0

Prompt Detail:

Here's an example code for implementing JWT token authentication in an ASP.NET Web Application:

  1. Install the required NuGet packages:
Microsoft.AspNet.WebApi.Core Microsoft.Owin.Security.Jwt Microsoft.Owin.Host.SystemWeb
  1. Create a JwtHelper class to generate and validate JWT tokens:
csharp
using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; public static class JwtHelper { private const string secretKey = "your-secret-key"; // replace with your secret key public static string GenerateToken(string username) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(secretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, username) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } public static bool ValidateToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(secretKey); try { tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero }, out SecurityToken validatedToken); return true; } catch (Exception) { return false; } } }
  1. Configure authentication in the Startup.cs file:
csharp
using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Jwt; using Owin; [assembly: OwinStartup(typeof(YourNamespace.Startup))] namespace YourNamespace { public class Startup { public void Configuration(IAppBuilder app) { var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtHelper.secretKey)), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero } }; app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions); } } }
  1. Use the Authorize attribute to secure your controllers or actions:
csharp
[Authorize] public class YourController : Controller { // your actions here }
  1. Generate and validate tokens in your login/logout actions:
csharp
public ActionResult Login(string username, string password) { // validate credentials if (isValidCredentials(username, password)) { var token = JwtHelper.GenerateToken(username); Response.Headers.Add("Authorization", "Bearer " + token); return RedirectToAction("Index", "Home"); } return View(); } [Authorize] public ActionResult Logout() { Response.Headers.Remove("Authorization"); return RedirectToAction("Login", "Account"); }

Note: This is just an example code and you may need to modify it to fit your specific requirements.

avatar
Parth Kavid
Shared 1 prompt
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
C#: Downloading YouTube Videos.
1 year ago 2023-03-29 16:32:33 b
0
0
C# Learning: Basics to API
8 months ago 2023-08-09 08:05:45 Abdulsalam Ahmad
0
93
C# Type Conversion Guide
8 months ago 2023-08-09 08:39:13 Ahmad Ayoola