Azure AD PostAuthentication добавить претензии
Я использую Azure AD для аутентификации пользователей. Я хочу добавить несколько пользовательских заявок, относящихся к моему приложению. Должен ли я сделать это в Application_PostAuthenticateRequest` в global.asax? Есть ли способ, которым я могу кэшировать свои претензии тоже?
3 ответа
Если вы используете промежуточное программное обеспечение ASP.NET OWIN, для этого есть специальные уведомления. Заявки, добавленные таким образом, попадут в файл cookie сеанса, так что вам не придется повторять логику дополнения заявок при последующих вызовах. См. http://www.cloudidentity.com/blog/2015/08/26/augmenting-the-set-of-incoming-claims-with-the-openid-connect-and-oauth2-middleware-in-katana-3-x/ для деталей.
Кстати, вы можете добавить свои собственные климы, но вы не можете переопределить существующие утверждения, добавленные Azure AD (что я видел до сих пор, может быть, я не прав). что вы можете сделать, это добавить новые климы, как это AuthorizationCodeReceived = context =>
{
List<System.Security.Claims.Claim> allcustomClaims = new List<System.Security.Claims.Claim>();
allcustomClaims.Add(new System.Security.Claims.Claim("customClaim", "YourDefindedValue"));
context.AuthenticationTicket.Identity.AddClaims(allcustomClaims);
return Task.FromResult(0);
}
и затем вы можете получить утверждение в любом месте контроллера, например, `@{
var argumentsIdentity = User.Identity как System.Security.Claims.ClaimsIdentity;
if (claimsIdentity != null)
{
var c = claimsIdentity.FindFirst("customClaim").Value;
}
} `спасибо
Вы можете дополнить претензии программно следующим образом:
public async Task<ActionResult> AuthenticateAsync()
{
ClaimsPrincipal incomingPrincipal = System.Threading.Thread.CurrentPrincipal as ClaimsPrincipal;
if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated == true)
{
ClaimsIdentity claimsIdentity = incomingPrincipal.Identity as ClaimsIdentity;
if (!claimsIdentity.HasClaim(ClaimTypes.Role, "Admin"))
{
claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "AADGuide"));
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
AuthenticateResult authResult = await authenticationManager.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
authenticationManager.SignIn(authResult.Properties,claimsIdentity);
}
}
return RedirectToAction("Index", "Start");
}
Это решение опирается на AuthenticationAsync
метод AuthenticationManager для получения оригинала AuthenticationProperties
, После получения свойств, вызовите SignIn
метод для сохранения нового ClaimsIdentity в auth cookie.
Если вы используете:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
...
Вот как мне удалось добавить дополнительные пользовательские претензии, используя new OAuthBearerAuthenticationProvider
:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
// The id of the client application that must be registered in Azure AD.
TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId },
// Our Azure AD tenant (e.g.: contoso.onmicrosoft.com).
Tenant = tenant,
Provider = new OAuthBearerAuthenticationProvider
{
// In this handler we can perform additional coding tasks...
OnValidateIdentity = async context =>
{
try
{
// Retrieve user JWT token from request.
var authorizationHeader = context.Request.Headers["Authorization"].First();
var userJwtToken = authorizationHeader.Substring("Bearer ".Length).Trim();
// Get current user identity from authentication ticket.
var authenticationTicket = context.Ticket;
var identity = authenticationTicket.Identity;
// Credential representing the current user. We need this to request a token
// that allows our application access to the Azure Graph API.
var userUpnClaim = identity.FindFirst(ClaimTypes.Upn);
var userName = userUpnClaim == null
? identity.FindFirst(ClaimTypes.Email).Value
: userUpnClaim.Value;
var userAssertion = new UserAssertion(
userJwtToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
identity.AddClaim(new Claim(identity.RoleClaimType, "myRole"));
}
catch (Exception e)
{
throw;
}
}
}
});
Для полного образца, проверьте этот пост в блоге.