Skip to content

Instantly share code, notes, and snippets.

@cocowalla
Last active November 9, 2018 15:49
Show Gist options
  • Save cocowalla/3c0bce7ddf761557c7d12d3281f4f964 to your computer and use it in GitHub Desktop.
Save cocowalla/3c0bce7ddf761557c7d12d3281f4f964 to your computer and use it in GitHub Desktop.
Attempt at adding a custom ClaimsIdentity to the Principal
builder.AddOpenIdConnect(options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
var db = ctx.HttpContext.RequestServices.GetRequiredService<DataContext>();
// Get the user's Azure Active Directory ID
var userId = Guid.Parse(ctx.Principal.FindFirst(OBJECT_ID_CLAIM_TYPE).Value);
// Find the user profile
var profile = await db.Users.SingleAsync(x => x.AzureId == userId);
// Add our app-specific identity to the list of identities known to the principal
var identity = new AppIdentity(ctx.Principal, profile);
ctx.Principal.AddIdentity(identity);
}
};
});
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => this.configuration.Bind("AzureAd", options))
.AddCookie(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.SlidingExpiration = true;
options.LoginPath = new PathString("/Account/SignIn");
options.LogoutPath = new PathString("/Account/SignOut");
options.AccessDeniedPath = new PathString("/Account/AccessDenied");
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
....
app.UseAuthentication();
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment