Skip to content

Instantly share code, notes, and snippets.

@mikeplate
Created December 13, 2018 11:35
Show Gist options
  • Save mikeplate/b484f3bdaf1632ca1d66b40d8fae8adf to your computer and use it in GitHub Desktop.
Save mikeplate/b484f3bdaf1632ca1d66b40d8fae8adf to your computer and use it in GitHub Desktop.
Add Azure AD authentication to existing ASP.NET Core application
// Startup.cs
using Microsoft.IdentityModel.Tokens;
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication().AddOpenIdConnect(c =>
{
c.Authority = "https://login.microsoftonline.com/common";
c.ClientId = "<insert-registered-guid>";
c.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false
};
c.Events.OnTokenValidated = async context =>
{
UserManager<ApplicationUser> manager = context.HttpContext.RequestServices.GetService<UserManager<ApplicationUser>>();
SignInManager<ApplicationUser> signIn = context.HttpContext.RequestServices.GetService<SignInManager<ApplicationUser>>();
ApplicationUser user = await manager.FindByNameAsync(context.Principal.Identity.Name);
if (user != null)
{
await signIn.SignInAsync(user, false);
}
};
});
}
// HomeController.cs
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
public class HomeController : Controller
{
[AllowAnonymous]
public IActionResult LoginWithAzure()
{
string redirectUrl = Url.Content("~/");
return Challenge(new AuthenticationProperties { RedirectUri = redirectUrl }, OpenIdConnectDefaults.AuthenticationScheme);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment