//设置Indetity
services.AddIdentity<ApplicationUser, IdentityRole>(IdentityOpts =>
{
// Password settings.
IdentityOpts.Password.RequireDigit = true;
IdentityOpts.Password.RequireLowercase = true;
IdentityOpts.Password.RequireNonAlphanumeric = true;
IdentityOpts.Password.RequireUppercase = true;
IdentityOpts.Password.RequiredLength = 6;
IdentityOpts.Password.RequiredUniqueChars = 1;
// Lockout settings.
IdentityOpts.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
IdentityOpts.Lockout.MaxFailedAccessAttempts = 5;
IdentityOpts.Lockout.AllowedForNewUsers = true;
// User settings.
IdentityOpts.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
IdentityOpts.User.RequireUniqueEmail = false;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();//默认Scheme Identity.Application
//设置Authentication
services.AddAuthentication(AuthOpts =>
{
AuthOpts.DefaultScheme = "MichaelAuth";
AuthOpts.DefaultSignInScheme = "MichaelAuth";
//AuthOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//AuthOpts.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
//AuthOpts.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//AuthOpts.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//AuthOpts.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie("MichaelAuth", CookieOpts => //增加Cookie Authentication
{
CookieOpts.Cookie.Name = "MichaelAuth.NetCoreApp";
CookieOpts.SlidingExpiration = true;
CookieOpts.LoginPath = "/Account/Login";
CookieOpts.ReturnUrlParameter = "RetMichael";
CookieOpts.ExpireTimeSpan = TimeSpan.FromSeconds(30);
自定义MachineKey或者其他密钥
//CookieOpts.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
CookieOpts.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context => //验证 票据Action
{
var Claims_Identity = context.HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity;
Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
"OnValidatePrincipal", context.Principal.Identity.Name);
return Task.CompletedTask;
}
};
});
//设置Identity.Application-Cookie过期时间
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromSeconds(30);
});
//解密票据
private IEnumerable<System.Security.Claims.Claim> GetClaimFromCookie(Microsoft.AspNetCore.Http.HttpContext httpContext, string cookieSchema="Identity.Application")
{
// Get the encrypted cookie value
var CookieOpt = httpContext.RequestServices.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<CookieAuthenticationOptions>>();
var CookieOptVal = CookieOpt.CurrentValue;
var cookieName = "MichaelAuth.NetCoreApp";// CookieOptVal.Cookie.Name;
var AuthSchemes = HttpContext.Authentication.GetAuthenticationSchemes();
var cookie = CookieOptVal.CookieManager.GetRequestCookie(httpContext, cookieName);
// Decrypt if found
if (!string.IsNullOrEmpty(cookie))
{
自定义MachineKey或者其他密钥
//var provider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
var provider = CookieOptVal.DataProtectionProvider;
var dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2");
var ticketDataFormat = new TicketDataFormat(dataProtector);
var ticket = ticketDataFormat.Unprotect(cookie);
#region MyRegion
var cookieManager = new ChunkingCookieManager();
var dataProtector0 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");
Get the decrypted cookie as plain text
//UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
//byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookie);
//byte[] plainBytes = dataProtector.Unprotect(protectedBytes);
//string plainText = specialUtf8Encoding.GetString(plainBytes);
//Get teh decrypted cookies as a Authentication Ticket
TicketDataFormat ticketDataFormat0 = new TicketDataFormat(dataProtector0);
AuthenticationTicket ticket0 = ticketDataFormat0.Unprotect(cookie);
#endregion
#region MyRegion
//Get a data protector to use with either approach
var dataProtector1 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");
Get the decrypted cookie as plain text
//UTF8Encoding specialUtf8Encoding1 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
//byte[] protectedBytes1 = Base64UrlTextEncoder.Decode(cookie);
//byte[] plainBytes1 = dataProtector.Unprotect(protectedBytes1);
//string plainText1 = specialUtf8Encoding.GetString(plainBytes1);
//Get the decrypted cookie as a Authentication Ticket
TicketDataFormat ticketDataFormat1 = new TicketDataFormat(dataProtector1);
AuthenticationTicket ticket1 = ticketDataFormat1.Unprotect(CookieOptVal.CookieManager.GetRequestCookie(httpContext, ".AspNetCore.Identity.Application"));
#endregion
#region MyRegion
//Get a data protector to use with either approach
var dataProtector2 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware");
//Get the decrypted cookie as a Authentication Ticket
TicketDataFormat ticketDataFormat2 = new TicketDataFormat(dataProtector2);
AuthenticationTicket ticket2 = ticketDataFormat2.Unprotect(cookie);
#endregion
return ticket?.Principal.Claims;
}
return null;
}