Skip to content

Instantly share code, notes, and snippets.

@supix
Last active November 15, 2022 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supix/e2d1e025ca4b0d90985176f9c5743658 to your computer and use it in GitHub Desktop.
Save supix/e2d1e025ca4b0d90985176f9c5743658 to your computer and use it in GitHub Desktop.
Enabling JWT integration in a net core WebApi project
{
//...
"tokenManagement": {
"secret": "Any String used to sign and verify JWT Tokens, Replace this string with your own Secret",
"issuer": "my.favourite.web.site.co.uk",
"audience": "SampleAudience",
"accessExpiration": 30,
"refreshExpiration": 60
},
//...
}
using Microsoft.AspNetCore.Http;
internal class GetLoggedUser : IGetLoggedUser
{
private readonly IHttpContextAccessor httpContextAccessor;
public GetLoggedUser(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public string Get()
{
var identity = this.httpContextAccessor.HttpContext.User.Identity;
if (identity.IsAuthenticated)
return identity.Name;
else
return null;
}
}
public void ConfigureServices(IServiceCollection services)
{
//...
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
var secret = Encoding.ASCII.GetBytes(token.Secret);
services.AddHttpContextAccessor();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secret),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false,
// the following line enables the possibility to read the logged username
// ('sub' claim in the JWT token) by reading User.Identity.Name property
NameClaimType = ClaimTypes.NameIdentifier
};
});
// Enable the following line in order to get debug messages in case of token decoding failure
// see https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/wiki/PII
// IdentityModelEventSource.ShowPII = true;
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
// this line integrates Microsoft Identity model
// e.g. a verified JWT enables the execution of
// actions marked with the [Authorize] attribute
app.UseAuthentication();
//...
}
[JsonObject("tokenManagement")]
public class TokenManagement
{
[JsonProperty("secret")]
public string Secret { get; set; }
[JsonProperty("issuer")]
public string Issuer { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("accessExpiration")]
public int AccessExpiration { get; set; }
[JsonProperty("refreshExpiration")]
public int RefreshExpiration { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment