You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.9 KiB
C#

using System.Security.Claims;
using AuthStudy.Authentication.Basic;
using AuthStudy.Authentication.Basic.Events;
using AuthStudy.Authentication.Browser;
namespace AuthStudy.WebApp
{
public class Program
{
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// 添加服务到IoC容器
builder.Services.AddControllers();
// Swagger 注册
builder.Services.AddSwaggerGen();
#region 认证注册
//接口实现注册
builder.Services.AddBrowserAuthentication
(
BrowserAuthenticationDefault.SchemeName,
BrowserAuthenticationDefault.DispayName,
new BrowserAuthenticationOptions()
{
AllowBrowsers = new List<string>() { "Edge" }
}
);
builder.Services
.AddAuthentication(AuthenticationSchemeList.BaseBrowserScheme)
//浏览器认证
.AddScheme<BrowserAuthenticationOptions, BrowserAuthenticationHandler>(AuthenticationSchemeList.BaseBrowserScheme, option =>
{
option.AllowBrowsers = new List<string>() { "Edge", "Chrome", "Firefox" };
})
//基本认证
.AddBasic(options =>
{
options.Realm = "Basic Authentication";
options.Events = new BasicAuthenticationEvents
{
OnValidateCredentials = context =>
{
if (context.Username == context.Password)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
}
return Task.CompletedTask;
}
};
});
//默认基类实现注册
#endregion
WebApplication app = builder.Build();
// 配置 Http 管道.
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
void Test()
{
}
}
}
}