Created
December 13, 2018 11:35
-
-
Save mikeplate/b484f3bdaf1632ca1d66b40d8fae8adf to your computer and use it in GitHub Desktop.
Add Azure AD authentication to existing ASP.NET Core application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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