Prompt Detail:
Here's an example code for implementing JWT token authentication in an ASP.NET Web Application:
- Install the required NuGet packages:
Microsoft.AspNet.WebApi.Core Microsoft.Owin.Security.Jwt Microsoft.Owin.Host.SystemWeb
- Create a
JwtHelper
class to generate and validate JWT tokens:
csharpusing 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;
}
}
}
- Configure authentication in the
Startup.cs
file:
csharpusing 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);
}
}
}
- Use the
Authorize
attribute to secure your controllers or actions:
csharp[Authorize]
public class YourController : Controller
{
// your actions here
}
- Generate and validate tokens in your login/logout actions:
csharppublic 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.
Add a comment