C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
JWT Token Generation Process in .Net Core Web API
WhatsApp
Bhuban Magar
6y
20.6
k
0
0
25
Blog
Simple JWT Token Generation
This is Controller Section of JWT Token Generation.
using
System;
using
System.Collections.Generic;
using
System.IdentityModel.Tokens.Jwt;
using
System.Linq;
using
System.Security.Claims;
using
System.Text;
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Authorization;
using
Microsoft.AspNetCore.Http;
using
Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Configuration;
using
Microsoft.IdentityModel.Tokens;
using
Models;
using
Repository.Interfaces;
using
CentralSageFlickApi.Helper;
namespace
CentralSageFlickApi.Controllers {
public
class
AccountController: ControllerBase {
private
readonly
IAccountService _accountService;
private
IConfiguration _config;
public
AccountController(IConfiguration config, IAccountService accountService) {
_config = config;
_accountService = accountService;
}#
region Token Generation
[AllowAnonymous]
[HttpPost]
[Route(
"~/api/Token/TokenGenerate"
)]
public
IActionResult Login([FromBody] LoginModel login) {
IActionResult response = Unauthorized();
try
{
if
(ModelState.IsValid) {
var user = AuthenticateUser(login.Username, login.AppCode);
if
(user !=
null
) {
var passwordString = PasswordGeneration.DecryptString(user.PasswordSalt, user.Password);
if
(login.Password.Equals(passwordString)) {
var tokenString = GenerateJwtToken(user);
response = Ok(
new
{
token = tokenString
});
}
else
{
response = BadRequest(
new
{
message =
"Invalid Password!"
});
}
}
else
{
response = BadRequest(
new
{
message =
"Invalid User!"
});
}
}
else
{
response = BadRequest(
new
{
message = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
.Select(v => v.ErrorMessage +
" "
+ v.Exception))
});
}
}
catch
(Exception ex) {
response = BadRequest(
new
{
message = ex.Message.ToString()
});
}
return
response;
}
private
string
GenerateJwtToken(UserRegisterModel userInfo) {
var securityKey =
new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[
"Jwt:Key"
]));
var credentials =
new
SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims =
new
[] {
new
Claim(ClaimTypes.Name, userInfo.Username),
new
Claim(ClaimTypes.Email, userInfo.Email),
new
Claim(ClaimTypes.NameIdentifier, userInfo.AppCode),
new
Claim(ClaimTypes.DateOfBirth, userInfo.AddedDate.ToString(
"yyyy-MM-dd"
)),
new
Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token =
new
JwtSecurityToken(issuer: _config[
"Jwt:Issuer"
],
audience: _config[
"Jwt:Audience"
],
claims: claims,
expires: DateTime.Now.AddMinutes(Convert.ToInt32(_config[
"Jwt:Expire"
])),
signingCredentials: credentials);
return
new
JwtSecurityTokenHandler().WriteToken(token);
}
private
UserRegisterModel AuthenticateUser(
string
userName,
string
appCode) {
UserRegisterModel user = _accountService.CheckUser(userName, appCode);
return
user;
}#
endregion
}
}
Startup.cs
This is Startup.cs file.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Authentication.JwtBearer;
using
Microsoft.AspNetCore.Builder;
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.AspNetCore.Http;
using
Microsoft.AspNetCore.HttpsPolicy;
using
Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Configuration;
using
Microsoft.Extensions.DependencyInjection;
using
Microsoft.Extensions.Logging;
using
Microsoft.Extensions.Options;
using
Microsoft.IdentityModel.Tokens;
using
Models;
using
Repository.Interfaces;
using
Repository.Services;
namespace
CentralSageFlickApi
{
public
class
Startup
{
public
Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public
IConfiguration Configuration {
get
; }
// This method gets called by the runtime. Use this method to add services to the container.
public
void
ConfigureServices(IServiceCollection services)
{
#region Add CORS
services.AddCors(options => options.AddPolicy(
"Cors"
, builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
#endregion
#region JwtToken Authentication
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new
TokenValidationParameters
{
ValidateIssuer =
true
,
ValidateAudience =
true
,
ValidateLifetime =
true
,
ValidateIssuerSigningKey =
true
,
ValidIssuer = Configuration[
"Jwt:Issuer"
],
ValidAudience = Configuration[
"Jwt:Audience"
],
IssuerSigningKey =
new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[
"Jwt:Key"
]))
};
});
#endregion
services.Configure<ReadConfig>(Configuration.GetSection(
"ConnectionString"
));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IAccountService, AccountService>();
services.AddTransient<ITheaterService, TheaterService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if
(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseCors(
"Cors"
);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
}
}
}
People also reading
Membership not found