Événements
Championnats du monde Power BI DataViz
14 févr., 16 h - 31 mars, 16 h
Avec 4 chances d’entrer, vous pourriez gagner un package de conférence et le rendre à la Live Grand Finale à Las Vegas
En savoir plusCe navigateur n’est plus pris en charge.
Effectuez une mise à niveau vers Microsoft Edge pour tirer parti des dernières fonctionnalités, des mises à jour de sécurité et du support technique.
Les modèles de stratégie d’authentification facilitent l’utilisation potentielle de plusieurs approches par un unique schéma d’authentification logique. Par exemple, un modèle de stratégie peut utiliser l’authentification Google pour les défis et l’authentification cookie pour tout le reste. Les modèles de stratégie d’authentification effectuent les opérations suivantes :
Tous les schémas d’authentification qui utilisent un AuthenticationSchemeOptions dérivé et le AuthenticationHandler<TOptions> associé :
public class AuthenticationSchemeOptions
{
/// <summary>
/// If set, this specifies a default scheme that authentication handlers should
/// forward all authentication operations to, by default. The default forwarding
/// logic checks in this order:
/// 1. The most specific ForwardAuthenticate/Challenge/Forbid/SignIn/SignOut
/// 2. The ForwardDefaultSelector
/// 3. ForwardDefault
/// The first non null result is used as the target scheme to forward to.
/// </summary>
public string ForwardDefault { get; set; }
/// <summary>
/// If set, this specifies the target scheme that this scheme should forward
/// AuthenticateAsync calls to. For example:
/// Context.AuthenticateAsync("ThisScheme") =>
/// Context.AuthenticateAsync("ForwardAuthenticateValue");
/// Set the target to the current scheme to disable forwarding and allow
/// normal processing.
/// </summary>
public string ForwardAuthenticate { get; set; }
/// <summary>
/// If set, this specifies the target scheme that this scheme should forward
/// ChallengeAsync calls to. For example:
/// Context.ChallengeAsync("ThisScheme") =>
/// Context.ChallengeAsync("ForwardChallengeValue");
/// Set the target to the current scheme to disable forwarding and allow normal
/// processing.
/// </summary>
public string ForwardChallenge { get; set; }
/// <summary>
/// If set, this specifies the target scheme that this scheme should forward
/// ForbidAsync calls to.For example:
/// Context.ForbidAsync("ThisScheme")
/// => Context.ForbidAsync("ForwardForbidValue");
/// Set the target to the current scheme to disable forwarding and allow normal
/// processing.
/// </summary>
public string ForwardForbid { get; set; }
/// <summary>
/// If set, this specifies the target scheme that this scheme should forward
/// SignInAsync calls to. For example:
/// Context.SignInAsync("ThisScheme") =>
/// Context.SignInAsync("ForwardSignInValue");
/// Set the target to the current scheme to disable forwarding and allow normal
/// processing.
/// </summary>
public string ForwardSignIn { get; set; }
/// <summary>
/// If set, this specifies the target scheme that this scheme should forward
/// SignOutAsync calls to. For example:
/// Context.SignOutAsync("ThisScheme") =>
/// Context.SignOutAsync("ForwardSignOutValue");
/// Set the target to the current scheme to disable forwarding and allow normal
/// processing.
/// </summary>
public string ForwardSignOut { get; set; }
/// <summary>
/// Used to select a default scheme for the current request that authentication
/// handlers should forward all authentication operations to by default. The
/// default forwarding checks in this order:
/// 1. The most specific ForwardAuthenticate/Challenge/Forbid/SignIn/SignOut
/// 2. The ForwardDefaultSelector
/// 3. ForwardDefault.
/// The first non null result will be used as the target scheme to forward to.
/// </summary>
public Func<HttpContext, string> ForwardDefaultSelector { get; set; }
}
La méthode AddPolicyScheme peut définir plusieurs schémas d’authentification et implémenter la logique pour sélectionner le schéma approprié en fonction des propriétés de jeton (par exemple, émetteur, revendications). Cette approche permet une plus grande flexibilité au sein d’une SEULE API.
services.AddAuthentication(options =>
{
options.DefaultScheme = Consts.MY_POLICY_SCHEME;
options.DefaultChallengeScheme = Consts.MY_POLICY_SCHEME;
})
.AddJwtBearer(Consts.MY_FIRST_SCHEME, options =>
{
options.Authority = "https://your-authority";
options.Audience = "https://your-audience";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidAudiences = Configuration.GetSection("ValidAudiences").Get<string[]>(),
ValidIssuers = Configuration.GetSection("ValidIssuers").Get<string[]>()
};
})
.AddJwtBearer(Consts.MY_AAD_SCHEME, jwtOptions =>
{
jwtOptions.Authority = Configuration["AzureAd:Authority"];
jwtOptions.Audience = Configuration["AzureAd:Audience"];
})
.AddPolicyScheme(Consts.MY_POLICY_SCHEME, displayName: null, options =>
{
options.ForwardDefaultSelector = context =>
{
string authorization = context.Request.Headers[HeaderNames.Authorization];
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer "))
{
var token = authorization.Substring("Bearer ".Length).Trim();
var jwtHandler = new JsonWebTokenHandler();
if(jwtHandler.CanReadToken(token)) // it's a self contained access token and not encrypted
{
var issuer = jwtHandler.ReadJsonWebToken(token).Issuer; //.Equals("B2C-Authority"))
if (issuer == Consts.MY_THIRD_PARTY_ISS) // Third party identity provider
{
return Consts.MY_THIRD_PARTY_SCHEME;
}
if (issuer == Consts.MY_AAD_ISS) // AAD
{
return Consts.MY_AAD_SCHEME;
}
}
}
// We don't know with it is
return Consts.MY_AAD_SCHEME;
};
});
L’exemple suivant montre un schéma de niveau supérieur combinant des schémas de niveau inférieur. L’authentification Google est utilisée pour les défis et l’authentification cookie pour tout le reste :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.ForwardChallenge = "Google")
.AddGoogle(options => { });
}
L’exemple suivant active la sélection dynamique de schémas en fonction des requêtes. Autrement dit, comment combiner les cookies aux authentifications de l’API :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// For example, can foward any requests that start with /api
// to the api scheme.
options.ForwardDefaultSelector = ctx =>
ctx.Request.Path.StartsWithSegments("/api") ? "Api" : null;
})
.AddYourApiAuth("Api");
}
Commentaires sur ASP.NET Core
ASP.NET Core est un projet open source. Sélectionnez un lien pour fournir des commentaires :
Événements
Championnats du monde Power BI DataViz
14 févr., 16 h - 31 mars, 16 h
Avec 4 chances d’entrer, vous pourriez gagner un package de conférence et le rendre à la Live Grand Finale à Las Vegas
En savoir plusEntrainement
Module
Sécuriser une application Web .Net avec l’infrastructure d’identité ASP.NET Core - Training
Découvrez comment ajouter l’authentification et l’autorisation à une application web .NET à l’aide du framework ASP.NET Core Identity.
Certification
Microsoft Certified: Identity and Access Administrator Associate - Certifications
Expliquez les fonctionnalités de Microsoft Entra ID pour moderniser des solutions d’identité, implémenter des solutions hybrides et une gouvernance des identités.
Documentation
Autoriser avec un schéma spécifique dans ASP.NET Core
Cet article explique comment limiter l’identité à un schéma spécifique lors de l’utilisation de plusieurs méthodes d’authentification.
Vue d’ensemble de l’authentification ASP.NET Core
En savoir plus sur l’authentification dans ASP.NET Core.
Présentation de l’autorisation dans ASP.NET Core
Découvrez les principes de base de l’autorisation et son fonctionnement dans les applications ASP.NET Core.