[ASP. NET] ClaimsIdentity parsing in ASP. NET Identity,

Source: Internet
Author: User

[ASP. NET] ClaimsIdentity parsing in ASP. NET Identity,

Hello, everyone :)

Recently, the author switched to ASP in zookeeper. NET Identity is used as the credential of the new system, and the information provided on the network is not complete. Therefore, it is used as a project, to avoid such problems. Write down some interesting topics

First of all, if you want to use ASP. NET Identity, you must use the following NuGet Security Suite

Microsoft. Owin. Host. SystemWeb

Microsoft. AspNet. Identity. Owin

Next, I add Startup to the App_Start resource. cs example, add the following program example (this is to test the settings in the case of using Identity directly, but in this case, there will be Startup. cs is split into two classes. Here I use a class Program)

Public void Configuration (IAppBuilder app)
{
ConfigureAuth (app );
}
Public void ConfigureAuth (IAppBuilder app)
{
// Cookie Auth
App. UseCookieAuthentication (new CookieAuthenticationOptions
{
AuthenticationType = defaauthauthenticationtypes. ApplicationCookie,
LoginPath = new PathString ("/Home/Index ")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
App. UseExternalSignInCookie (defaauthauthenticationtypes. ApplicationCookie );
}

Next, let's look at Web. config configurations in the example.

<System. web>
<Authentication mode = "None"/>
------------------------------------------------------
<System. webServer>
<Modules>
<Remove name = "FormsAuthenticationModule"/>
</Modules>

There are two logon methods for logon. Both of them are acceptable, but I will pay attention to the next few points.

// Extract method of AuthenticationManager

HttpContext. GetOwinContext (). Authentication;

// Clear the previous login information

AuthenticationManager. SignOut (defaauthauthenticationtypes. ApplicationCookie );

// First

IList <Claim> claims = new List <Claim> ();

Claims. Add (new Claim (ClaimTypes. NameIdentifier, Request ["userName"]. ToString ()));

Claims. Add (new Claim (ClaimTypes. Name, Request ["userName"]. ToString ()));

Claims. Add (new Claim (ClaimTypes. Role, "Users "));

ClaimsIdentity identity = new ClaimsIdentity (claims,

DefaultAuthenticationTypes. ApplicationCookie );

// Second

ClaimsIdentity claimsIdentity = new ClaimsIdentity (defaauthauthenticationtypes. ApplicationCookie, ClaimTypes. NameIdentifier, ClaimTypes. Role );

ClaimsIdentity. AddClaim (new Claim (ClaimTypes. NameIdentifier, "MyCustomID "));

ClaimsIdentity. AddClaim (new Claim (ClaimTypes. Name, "MyCustomUser "));

ClaimsIdentity. AddClaim (new Claim (
ClaimTypes. NameIdentifier, Request ["userName"]. ToString (),
"Http://www.w3.org/2001/XMLSchema#string "));


ClaimsIdentity. AddClaim (
New Claim ("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider ",
"My Identity", "http://www.w3.org/2001/XMLSchema#string "));

// Here, I strongly suggest using the second attack method, because if your attack surface uses the antiforgerytoken to prevent CSRF attacks, the first method will generate an attack

// However, if the second method is used and the identityprovider Claim is added. It can be used normally, but as mentioned at the bottom of this article, we can see through Global. asax. cs is added to the parameter data settings, if it passes through Global. asax. if cs is used, there is no problem with the above two methods :)

// Login

AuthenticationManager. SignIn (new AuthenticationProperties () {IsPersistent = true}, identity );

----------------------------- Click here -------------------------------

When I was looking for information, I found that some responses on StackOverFlow were actually incorrect...

For example

Http://stackoverflow.com/questions/18801120/where-is-microsoft-aspnet-identity-owin-authenticationmanager-in-asp-net-identit

Private async Task SignInAsync (ApplicationUser user, bool isPersistent ){

AuthenticationManager. SignOut (defaauthauthenticationtypes. ExternalCookie );

Var identity = await UserManager. CreateIdentityAsync (user, defaauthauthenticationtypes. ApplicationCookie );

AuthenticationManager. SignIn (new AuthenticationProperties () {IsPersistent = isPersistent}, identity );

}

In fact, what he mentioned is not complete. Where is the problem? Problem in our Startup. cs

App. UseCookieAuthentication (new CookieAuthenticationOptions

{

AuthenticationType =DefaultAuthenticationTypes. ApplicationCookie,

LoginPath = new PathString ("/Home/Index ")

});

// Use a cookie to temporarily store information about a user logging in with a third party login provider

// In fact, this section is similar to the above.

App. UseExternalSignInCookie (defaauthauthenticationtypes. ExternalCookie );

In fact, ClaimsIdentity is used as the Cookie name region in the rough body at the end. This is also because, if you specify the name and Startup in the SignOut method. cs. Will cause youUnable to log out normallyPrevious user information! (Important)

You can skip this article if you are interested.

CookieAuthenticationMiddelware: cookie Encryption Method

As for Startup. cs mentioned by zookeeper, the actual app. UseExternalSignInCookie and app. UseCookieAuthentication can only be selected. Let's take a look at UseExternalSignInCookie. The original website will find that his work is actually similar to UseCookieAuthentication.

Public static void UseExternalSignInCookie (this IAppBuilder app, string externalAuthenticationType ){

If (app = null ){

Throw new ArgumentNullException ("app ");

}

App. setdefasigsigninasauthenticationtype (externalAuthenticationType );

App. UseCookieAuthentication (new CookieAuthenticationOptions {

AuthenticationType = externalAuthenticationType,

AuthenticationMode = AuthenticationMode. Passive,

CookieName = CookiePrefix + externalAuthenticationType,

ExpireTimeSpan = TimeSpan. FromMinutes (5 ),

});

}

Outbound

The CookieName settings we mentioned above in the Root Node also know that if we use ClaimsIdentity to log on, CookieName should also start up. set cs, otherwise you will find that it is correct to clearly program login, why cannot you log on to y?

ClaimsIdentity claimsIdentity = new ClaimsIdentity (DefaultAuthenticationTypes. ApplicationCookie, ClaimTypes. NameIdentifier, ClaimTypes. Role );

In addition, if you accidentally encounter the AntiForgery attack (this is a method provided by microservices to prevent CSRF attacks)

You can add Appliccation_Start in Global. asax. cs instances. ClaimTypes: What kind of Types does your ClaimsIdentity have?

AntiForgeryConfig. UniqueClaimTypeIdentifier = ClaimTypes. NameIdentifier;

The above is a simple ClaimsIdentity experience. We will see it below :)

Exam:

Http://www.cnblogs.com/jesse2013/p/aspnet-identity-claims-based-authentication-and-owin.html#protectcookie

Https://github.com/MohammadYounes/MVC5-MixedAuth/issues/20

Http://dotnetcodr.com/2013/02/11/introduction-to-claims-based-security-in-net4-5-with-c-part-1/

Http://stackoverflow.com/questions/19977833/anti-forgery-token-issue-mvc-5

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.