Last active
August 29, 2022 21:47
-
-
Save bradygaster/79973bd51f739db648aca5deb5989b96 to your computer and use it in GitHub Desktop.
How to authenticate ASP.NET with GitHub
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
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authentication.Cookies; | |
using System.Security.Claims; | |
var signin = "/signin"; | |
var signout = "/signout"; | |
var callback = "/signin-github"; | |
var redirectUrl = "/"; | |
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddRazorPages(); | |
// wire up the github auth | |
builder.Services.AddAuthentication(options => | |
{ | |
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |
}) | |
.AddCookie(options => | |
{ | |
options.LoginPath = signin; | |
options.LogoutPath = signout; | |
}) | |
.AddGitHub(options => | |
{ | |
options.ClientId = builder.Configuration.GetValue<string>("GitHubClientId"); | |
options.ClientSecret = builder.Configuration.GetValue<string>("GitHubClientSecret"); | |
options.Scope.Add("read:user"); | |
options.Scope.Add("gist"); | |
options.CallbackPath = callback; | |
options.Events.OnCreatingTicket += context => | |
{ | |
if (context.AccessToken is not null) | |
{ | |
var login = context.User.GetString("login"); | |
var gitHubId = context.User.GetString("id"); | |
var avatar = context.User.GetString("avatar_url"); | |
var name = context.User.GetString("name"); | |
context.Identity?.AddClaim(new Claim("access_token", context.AccessToken)); | |
context.Identity?.AddClaim(new Claim("avatar_url", avatar)); | |
context.Identity?.AddClaim(new Claim("full_name", name)); | |
context.Identity?.AddClaim(new Claim("github_id", gitHubId)); | |
} | |
return Task.CompletedTask; | |
}; | |
}); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (!app.Environment.IsDevelopment()) | |
{ | |
app.UseExceptionHandler("/Error"); | |
} | |
// map the signin and signout endpoints | |
app.MapGet(signin, async (HttpContext httpContext) | |
=> await httpContext.ChallengeAsync("GitHub",new AuthenticationProperties { RedirectUri = redirectUrl }) | |
); | |
app.MapGet(signout, async (HttpContext httpContext) | |
=> await httpContext.SignOutAsync(new AuthenticationProperties { RedirectUri = redirectUrl }) | |
); | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.MapRazorPages(); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment