45 lines
1.7 KiB
C#
45 lines
1.7 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using WebNovelPortal.Authentication;
|
|
|
|
namespace Common.Authentication.OIDC;
|
|
|
|
public static class AuthenticationExtension
|
|
{
|
|
public static void AddOIDCAuth(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
var oidcConfig = configuration.GetRequiredSection(OpenIdConnectAuthenticationOptions.ConfigurationSection)
|
|
.Get<OpenIdConnectAuthenticationOptions>();
|
|
services.AddAuthentication(opt =>
|
|
{
|
|
opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
|
|
})
|
|
.AddCookie()
|
|
.AddOpenIdConnect(opt =>
|
|
{
|
|
opt.Authority = oidcConfig.Authority;
|
|
opt.ClientId = oidcConfig.ClientId;
|
|
opt.ClientSecret = oidcConfig.ClientSecret;
|
|
|
|
opt.ResponseType = OpenIdConnectResponseType.Code;
|
|
opt.GetClaimsFromUserInfoEndpoint = false;
|
|
opt.SaveTokens = true;
|
|
opt.UseTokenLifetime = true;
|
|
foreach (var scope in oidcConfig.Scopes.Split(" "))
|
|
{
|
|
opt.Scope.Add(scope);
|
|
}
|
|
|
|
opt.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
NameClaimType = ClaimTypes.Name
|
|
};
|
|
});
|
|
}
|
|
} |