Skip to content

Instantly share code, notes, and snippets.

@jaredpar
Created April 12, 2023 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredpar/ed707669907dd908e866189c6467e0bc to your computer and use it in GitHub Desktop.
Save jaredpar/ed707669907dd908e866189c6467e0bc to your computer and use it in GitHub Desktop.
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(o =>
{
// set the path for the authentication challenge
o.LoginPath = "/signin";
// set the path for the sign out
o.LogoutPath = "/signout";
})
.AddGitHub(o =>
{
o.ClientId = builder.Configuration["github:clientId"]!;
o.ClientSecret = builder.Configuration["github:clientSecret"]!;
o.CallbackPath = "/signin-github";
// Grants access to read a user's profile data.
// https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
o.Scope.Add("read:user");
// Optional
// if you need an access token to call GitHub Apis
o.Events.OnCreatingTicket += context =>
{
if (context.AccessToken is { })
{
context.Identity?.AddClaim(new Claim("access_token", context.AccessToken));
}
return Task.CompletedTask;
};
});
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapGet("/signout", async ctx =>
{
await ctx.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = "/"
});
});
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment