In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to implement Identity authentication in asp.net core". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to implement Identity authentication for asp.net core".
1. Authentication
There are two common modes of asp.net core authentication: JwtBearer and Cookie. In this article, we will enable Cookie as the preservation of identity information. So, how do we enable it?
Add the following to the ConfigureServices (IServiceCollection services) method of Startup.cs:
Services.AddAuthentication (CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie (CookieAuthenticationDefaults.AuthenticationScheme, options = >
{
Configuration.Bind ("CookieSettings", options)
});
At this point, you can start a permission verification, and when a user visits a page or interface that needs to be authenticated, if he is not logged in, it will automatically jump to:
Https://localhost:5001/Account/Login?ReturnUrl=XXXX
Where ReturnUrl points to the source page.
1.1 setting validation
When we enable authentication in the Startup class, not all access interfaces are redirected to the login page. So how do you set the access path that requires authentication? Asp.net core provides us with a feature class:
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
Public class AuthorizeAttribute: Attribute, IAuthorizeData
{
Public string Policy {get; set;}
Public string Roles {get; set;}
Public string AuthenticationSchemes {get; set;}
}
As you can see, this property class is allowed to be set on classes and methods, and more than one can be set to allow subclasses to inherit the properties of the parent class. So you can set [Authorize] on the controller, and when it is set on the controller, all Action in the access controller will require authentication; it can also be set separately on the Action, indicating that the Action needs to be verified, and other methods in the controller do not need verification.
1.2 setting ignore
In the process of development, we will encounter a set of links or pages: the request address belongs to the same controller, but one of the addresses can be accessed without the user logging in. Usually, in order to reduce repetitive code and reusability, we set authentication requirements directly on the controller, rather than adding authentication requirements on all Action in the controller.
So, how can we let go of one of the requests and allow it to be authenticated?
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
Public class AllowAnonymousAttribute: Attribute, IAllowAnonymous
{
}
If you take a closer look, you can see that this property can be set on classes and methods, and it is not allowed to be set multiple times, allowing subclasses to inherit the properties of the parent class.
There is nothing to say about the use of this feature, but it is important to be careful not to use it with AuthorizeAttribute. Although there is no problem with the compilation, it can actually mislead the programmer's logic to a certain extent.
two。 Save identity
If you have authentication, you must save your identity. When we get the user information from the database or other three-party services, we need to save the user information instead of asking the user or service provider for information every time.
In asp.net core, there is an attribute in the Controller class:
Public HttpContext HttpContext {get;}
HttpContext provides an extension method that can be used to save user information:
Public static Task SignInAsync (this HttpContext context, ClaimsPrincipal principal)
The return type of this method is temporarily ignored, which accepts a parameter of type ClaimsPrincipal. Let's take a look at the basics of this category:
Public class ClaimsPrincipal: IPrincipal
{
Public ClaimsPrincipal ()
Public ClaimsPrincipal (IEnumerable identities)
Public ClaimsPrincipal (BinaryReader reader)
Public ClaimsPrincipal (IIdentity identity)
Public ClaimsPrincipal (IPrincipal principal)
Public static ClaimsPrincipal Current {get;}
Public static Func ClaimsPrincipalSelector {get; set;}
Public static Func PrimaryIdentitySelector {get; set;}
Public virtual IIdentity Identity {get;}
Public virtual IEnumerable Identities {get;}
Public virtual IEnumerable Claims {get;}
Public virtual void AddIdentities (IEnumerable identities)
Public virtual void AddIdentity (ClaimsIdentity identity)
Public virtual ClaimsPrincipal Clone ()
Public virtual IEnumerable FindAll (Predicate match)
Public virtual IEnumerable FindAll (string type)
Public virtual Claim FindFirst (string type)
Public virtual Claim FindFirst (Predicate match)
Public virtual bool HasClaim (Predicate match)
Public virtual bool HasClaim (string type, string value)
Public virtual bool IsInRole (string role)
Public virtual void WriteTo (BinaryWriter writer)
}
There are a lot of methods and properties, so let's focus on constructors and methods that can start with AddXXX.
Here is a trick: for a strange class, the constructor is a very important feature of the class itself, and we can use the constructor to analyze what basic data the class needs.
So, through a simple analysis, we need to continue to understand these two classes:
Public class ClaimsIdentity: IIdentity
{
Public ClaimsIdentity ()
Public ClaimsIdentity (string authenticationType)
Public ClaimsIdentity (IIdentity identity)
Public ClaimsIdentity (IEnumerable claims)
Public ClaimsIdentity (IEnumerable claims, string authenticationType)
Public ClaimsIdentity (IIdentity identity, IEnumerable claims)
Public ClaimsIdentity (string authenticationType, string nameType, string roleType)
Public ClaimsIdentity (IEnumerable claims, string authenticationType, string nameType, string roleType)
Public ClaimsIdentity (IIdentity identity, IEnumerable claims, string authenticationType, string nameType, string roleType)
}
Public class Claim
{
Public Claim (BinaryReader reader)
Public Claim (BinaryReader reader, ClaimsIdentity subject)
Public Claim (string type, string value)
Public Claim (string type, string value, string valueType)
Public Claim (string type, string value, string valueType, string issuer)
Public Claim (string type, string value, string valueType, string issuer, string originalIssuer)
Public Claim (string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject)
Protected Claim (Claim other)
Protected Claim (Claim other, ClaimsIdentity subject)
Public string Type {get;}
Public ClaimsIdentity Subject {get;}
Public IDictionary Properties {get;}
Public string OriginalIssuer {get;}
Public string Issuer {get;}
Public string ValueType {get;}
Public string Value {get;}
Protected virtual byte [] CustomSerializationData {get;}
Public virtual Claim Clone ()
Public virtual Claim Clone (ClaimsIdentity identity)
Public override string ToString ()
Public virtual void WriteTo (BinaryWriter writer)
Protected virtual void WriteTo (BinaryWriter writer, byte [] userData)
}
So, if you look at this, you will find that we can save the information in the following ways:
List claims = null
Var identity = new ClaimsIdentity (claims, CookieAuthenticationDefaults.AuthenticationScheme)
HttpContext.SignInAsync (CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal (identity))
At this point, the data can be saved in the Cookie, so how to get the data in the controller:
Public ClaimsPrincipal User {get;}
In the controller, such an attribute is provided, and of course, if you want to get the value correctly, you need to add the following configuration to the Startup.cs class:
Public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
/ /. Omit other configurations
App.UseAuthorization ()
App.UseAuthentication ()
/ /. Omit other configurations
} at this point, I believe you have a deeper understanding of "how to implement Identity authentication in asp.net core". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.