I am trying to implement Azure AD B2C auth on my endpoints using Azure Functions.
When I call https://{MyAzureAd}.b2clogin.com/{MyAzureAd}.onmicrosoft.com/{Flow}/oauth2/v2.0/token
I got this result...
{
"access_token": "...",
"token_type": "Bearer",
"expires_in": "3600",
"refresh_token": "..."
}
The access token is a JWT.... Now I need to checjk if the token is really valid, but I don't know how or where the secret is located....
I gone already to https://login.microsoftonline.com/{TenantId}/.well-known/openid-configuration and got the x5c to use as certificate, but it's not working...Any clue? this is my code...
if (!req.Headers.ContainsKey("Authorization"))
{
Console.WriteLine("No Authorization hader");
return new UnauthorizedResult();
}
string authorizationHeader = req.Headers["Authorization"];
if (string.IsNullOrEmpty(authorizationHeader))
{
Console.WriteLine("Authorization is null");
return new UnauthorizedResult();
}
IDictionary<string, object> claims = null;
try
{
Console.WriteLine(authorizationHeader);
if (authorizationHeader.StartsWith("Bearer"))
{
authorizationHeader = authorizationHeader.Substring(7);
}
Console.WriteLine(authorizationHeader);
// Validate the token and decode the claims.
claims = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret("Where on Azure Portal can I get this ????")
.MustVerifySignature()
.Decode<IDictionary<string, object>>(authorizationHeader);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
return new UnauthorizedResult();
}
string Username = Convert.ToString(claims["username"]);
string Role = Convert.ToString(claims["role"]);
Console.WriteLine(Username, Role);
In your title you ask for "Decoding", but in your post you ask for "Validating" a token.
For decoding you only need base64 with some char replacements, you can even do that on frontend without a problem:
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const decodedToken = JSON.parse(atob(base64));
For validation, aspnet has inbuildt middleware that handles it for you:
// in ConfigureServices
services.AddAuthentication(o => o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.Authority = Configuration["B2cAuthority"];
o.Audience = Configuration["B2cAudience"];
});
// in Configure
app.UseAuthentication();
In Azure Functions you can use it almost identically as outlined here: https://blog.darkloop.com/post/bringing-authorizeattribute-to-net-azure-functions-v2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.