6. How to use the official nuget package to implement cookie login and nugetcookie
"Microsoft. AspNetCore. Authentication. Cookies": "1.0.0 ",
Here we need to use this nuget package
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", LoginPath = new PathString("/Admin/Account/Login/"), AccessDeniedPath = new PathString("/Admin/Home/Index/"), AutomaticAuthenticate = true, AutomaticChallenge = true, CookiePath = "/" }); }
Add in startup. cs
Here we will explain the cookie name corresponding to AuthenticationScheme.
If LoginPath is not logged on, the path to the login page
Page returned by AccessDeniedPath if the permission is insufficient
CookiePath: the range of cookie availability. I have never used this function. It should be able to distinguish between foreground and background login.
I am not very clear about the other few.
How do I write the login method?
var identity = new ClaimsIdentity("AccountLogin");identity.AddClaim(new Claim(ClaimTypes.Name, "Test"));identity.AddClaim(new Claim("AccountID", "1"));identity.AddClaim(new Claim("Modules", "1,2,3"));identity.AddClaim(new Claim(ClaimTypes.Role,"Admin"));ClaimsPrincipal principal = new ClaimsPrincipal(identity);await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal, new AuthenticationProperties{ IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(20),});
The above is the information that can be customized to store cookies.
So how to retrieve data in the program? I recommend using the extension method.
Public static class UserExtension {// <summary> // obtain the User ID // </summary> /// <param name = "User"> </param> // /<returns> </returns> public static int GetAccountID (this ClaimsPrincipal User) {var accountID = User. findFirst ("AccountID "). value; return Convert. toInt32 (accountID );}}
Introduce this class to controller and view
View reference can be directly added to _ ViewImports. cshtml
@ Using MySqlDemo. Extend // The UserExtension is referenced here.
@ Using MySqlDemo. ViewModels @ addTagHelper *, Microsoft. AspNetCore. Mvc. TagHelpers @ inject Microsoft. ApplicationInsights. Extensibility. TelemetryConfiguration
In this way, you can directly use User. GetAccountID () to obtain the User ID.
You can use or use Roles to determine the role to log on, but the string must be exactly the same. This does not support the determination that the user has multiple Roles. If you need to write the extension method yourself
[Authorize (Roles = "SuperAdmin")]
Log out
Await HttpContext. Authentication. SignOutAsync ("MyCookieMiddlewareInstance ");