Reputation: 2229
Hi I am developing web application in .Net core. I have implemented V2 Authentication. Now I have requirement to add Authorization. The requirement states that First,
It should not be the job of the application to gather the claims of the user, they should be available in the users JWT. Second, Permissions with an application will be granted based on claims.
Below is my authentication code.
services
.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = azureActiveDirectoryOptions.Authority;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new List<string>
{
azureActiveDirectoryOptions.AppIdUri,
azureActiveDirectoryOptions.ClientId
},
};
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Can someone help me to add claims based Authorization? Any help would be greatly appreciated. Thanks
Upvotes: 2
Views: 9992
Reputation: 27528
For authorization part , you can add app roles in your application , assign roles to users/groups , so that roles
will include in token after user login and consent , your application could use policy to restrict access based on roles
claim .
Another approach is to use Azure AD Groups and Group Claims . The difference is your application should check groups
claim ,
Upvotes: 1
Reputation: 20067
You could use code as below to add custom claim in JWT token.
public string createToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", "joey"),
new Claim("Email","[email protected]")
});
const string sec = "yoursecurityKey";
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var jwtSecurityToken = handler.CreateJwtSecurityToken(
"issuer",
"Audience",
new ClaimsIdentity(claimsIdentity),
DateTime.Now,
DateTime.Now.AddHours(1),
DateTime.Now,
signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
For more details, you could refer to this article.
Update:
If so, you could use JwtBearerEvents to add claim.
.AddJwtBearer(o =>
{
//Additional config snipped
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
//Get the calling app client id that came from the token produced by Azure AD
string clientId = ctx.Principal.FindFirstValue("appid");
var claims = new List<Claim>
{
new Claim("UserName", "joey")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
};
});
Upvotes: 5