6. How to use the official nuget package to implement cookie login and nugetcookie

Source: Internet
Author: User

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 ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.