Created
October 14, 2024 17:19
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Configure OAuth authentication | |
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | |
.AddJwtBearer(options => | |
{ | |
options.Events = new JwtBearerEvents() | |
{ | |
OnAuthenticationFailed = ctx => | |
{ | |
Console.WriteLine("Authentication failed"); | |
Console.WriteLine(ctx.Exception.Message); | |
return Task.CompletedTask; | |
} | |
, | |
OnMessageReceived = msg => | |
{ | |
var token = msg?.Request.Headers.Authorization.ToString(); | |
string path = msg?.Request.Path ?? ""; | |
if (!string.IsNullOrEmpty(token)) | |
{ | |
Console.WriteLine("Access token"); | |
Console.WriteLine($"URL: {path}"); | |
Console.WriteLine($"Token: {token}\r\n"); | |
} | |
else | |
{ | |
Console.WriteLine("Access token"); | |
Console.WriteLine("URL: " + path); | |
Console.WriteLine("Token: No access token provided\r\n"); | |
} | |
return Task.CompletedTask; | |
} | |
, | |
OnTokenValidated = ctx => | |
{ | |
Console.WriteLine(); | |
Console.WriteLine("Claims from the access token"); | |
if (ctx?.Principal != null) | |
{ | |
foreach (var claim in ctx.Principal.Claims) | |
{ | |
Console.WriteLine($"{claim.Type} - {claim.Value}"); | |
} | |
} | |
Console.WriteLine(); | |
return Task.CompletedTask; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment