HOS.Web.Security 1.0.2
JWT Authenication
Usage:-
Please add in the startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddJwtBearer(this.Configuration, "JwtOptions", async (context) => {
var tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService<ITokenValidatorService>();
return await tokenValidatorService.ValidateAsync(context);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
// app.UseSwagger();
// app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HOSLibraryAppln v1"));
//}
//app.UseHttpsRedirection();
//app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
//const string cacheMaxAge = "604800";
//app.UseStaticFiles(new StaticFileOptions
//{
// OnPrepareResponse = ctx =>
// {
// ctx.Context.Response.Headers.Add("Cache-Control", $"public, max-age={cacheMaxAge}");
// }
//});
//app.UseDefaultFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
-----------------------Sample Code-------------------
[Authorize()]
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
IJwtTokenFactory _jwtTokenFactory = null;
public AuthController(IJwtTokenFactory jwtTokenFactory)
{
this._jwtTokenFactory = jwtTokenFactory;
}
[AllowAnonymous]
[HttpPost("sign-in")]
public async Task<TokenResult> SigninAsync()
{
return await Task.FromResult<TokenResult>(new TokenResult
{
IsValid = true,
Token = this._jwtTokenFactory.CreateJwtToken(new JwtUser { ID = "A001", Name = "Linto" })
});
}
[HttpPost("check-user-info")]
public object CheckUserInfo()
{
var user = this.HttpContext.GetUser();
if (user == null)
return new { Status = "Failed" };
else
return new { Status = "Success", User = user };
}
[AllowAnonymous]
[HttpPost("refresh-token")]
public async Task<TokenResult> RefreshTokenAsync([FromBody] UserToken userToken)
{
if(!this._jwtTokenFactory.IsvalidRefreshToken(userToken.AccessToken, userToken.RefreshToken))
{
return new TokenResult { IsValid = false};
}
return await Task.FromResult<TokenResult>(new TokenResult
{
IsValid = true,
Token = this._jwtTokenFactory.CreateJwtToken(this._jwtTokenFactory.GetJwtTokenInfo(userToken.AccessToken).User)
});
}
}
--------------------------------Sample Api -----------------------------
[Route("api/[controller]")]
[ApiController]
public class ApiKeyController : ControllerBase
{
[HttpGet("GetSystemDate")]
public string GetSystemDate()
{
return DateTime.Now.ToString("dd MMM yyyy HH:mm");
}
[ApiKey()]
[HttpGet("GetSecuredSystemDate")]
public string GetSecuredSystemDate()
{
return $"Secured: {DateTime.Now.ToString("dd MMM yyyy HH:mm")}"; ;
}
[ApiKey(SecretKeyName: "ApiKey1")]
[HttpGet("GetSecuredSystemDateEx")]
public string GetSecuredSystemDateEx()
{
return $"Secured EX: {DateTime.Now.ToString("dd MMM yyyy HH:mm")}"; ;
}
}
No packages depend on HOS.Web.Security.
.NET 6.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 6.0.3)
- Microsoft.Extensions.Configuration.Abstractions (>= 6.0.0)
- Microsoft.Extensions.Options (>= 6.0.0)
- System.IdentityModel.Tokens.Jwt (>= 6.16.0)