In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to make ASP.NETCore and ASP.NETFramework share authentication, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
.net Core has been hot for a while, and its usability is getting higher and higher after the release of version 1.1. Open source, componentized, cross-platform, excellent performance, active community and other tags plus "Microsoft Dad" main tweets and strong support, although compared to .net framework at this stage is still relatively "immature", but you can imagine its bright future. As a. Net developer, have you started trying to migrate the project to. Net core? One of the bigger problems to be solved is how to make your. Net core and old. Net framework sites compatible with authentication!
1. The first chapter
Let's first take a look at the implementation of identity in. Net core and configure the relevant properties of Cookie authentication in the Configure of Startup.cs.
Public void Configure (IApplicationBuilder app, IHostingEnvironment env) {app.UseCookieAuthentication (new CookieAuthenticationOptions {AuthenticationScheme = "test", CookieName = "MyCookie"});}
Controller
Public IActionResult Index () {return View ();} public IActionResult Login () {return View ();} [HttpPost] public async Task Login (string name) {var identity = new ClaimsIdentity (new List {new Claim (ClaimTypes.Name,name, ClaimValueTypes.String)}, ClaimTypes.Authentication, ClaimTypes.Name, ClaimTypes.Role); var principal = new ClaimsPrincipal (identity) Var properties = new AuthenticationProperties {IsPersistent = true}; await HttpContext.Authentication.SignInAsync ("test", principal, properties); return RedirectToAction ("Index");}
Login view
Log in
Index view
Welcome to-@ User.Identity.Name @ if (User.Identity.IsAuthenticated) {
Login successful!
}
The following is a screenshot of the effect:
Ok, so far we have realized the saving and reading of user authentication information easily with. Net core.
Then think, what should I do if my. Net framework project wants to read the authentication information saved by the. Net core project?
At least three conditions are required for both projects to accept the same Identity:
The CookieName must be the same.
The domain name of Cookie must be the same.
Cookie certification for both projects must use the same Ticket.
First, let's add the domain attribute and the ticket attribute to the Cookie authentication of. Net core.
Public void Configure (IApplicationBuilder app, IHostingEnvironment env) {var protectionProvider = DataProtectionProvider.Create (new DirectoryInfo (@ "C:\ keyPath\"); var dataProtector = protectionProvider.CreateProtector ("MyCookieAuthentication"); var ticketFormat = new TicketDataFormat (dataProtector); app.UseCookieAuthentication (new CookieAuthenticationOptions {AuthenticationScheme = "test", CookieName = "MyCookie", CookieDomain = "localhost", TicketDataFormat = ticketFormat});}
At this point, we perform a user login in the. Net core project, and the program will generate key.xml in the directory we specified.
Let's open the file and see that the program helped us record that information.
2016-12-04T08:27:27.8435415Z 2016-12-04T08:27:27.8214603Z 2017-03-04T08:27:27.8214603Z yHdMEYlEBzcwpx0bRZVIbcGJ45/GqRwFjMfq8PJ+k7ZWsNMic0EMBgP33FOq9MFKX0XE/a1plhDizbb92ErQYw==
Ok, then we start to configure the. Net framework project, and again, configure the relevant properties of Cookie authentication in Startup.cs.
Public partial class Startup {public void Configuration (IAppBuilder app) {var protectionProvider = DataProtectionProvider.Create (new DirectoryInfo (@ "C:\ keyPath\"); var dataProtector = protectionProvider.CreateProtector ("MyCookieAuthentication"); var ticketFormat = new AspNetTicketDataFormat (new DataProtectorShim (dataProtector)); app.UseCookieAuthentication (new CookieAuthenticationOptions {AuthenticationType = "test", CookieName = "MyCookie", CookieDomain = "localhost", TicketDataFormat = ticketFormat});}}
View
Welcome to .net framewor-@ User.Identity.Name @ if (User.Identity.IsAuthenticated) {
.net framework login successful!
}
The method of writing is basically the same as the. net core, let's see if we can successfully get the user name:
On the contrary, the method of logging in. Net framework and getting authentication information in. Net core is the same, so I won't repeat it here.
However, is this the end of the matter? Unfortunately, the trouble has only just begun!
2. Second chapter
If you do not have many subprojects and are not complex, add a. Net core site, and then modify the previous. Net framework site appropriately, the above examples can really meet the requirements. But if you have enough subsites, or if the project is too complex, and the business involved is too large or important, we usually don't want to move on the old project. In other words, we have no way to change all the projects and launch at the same time as the new. Net core site, if we do, the update cycle will be very long, and the maintenance phase after testing and update will be very stressful. So we have to find a way to make. Net core's authentication mechanism fully cater to. Net framwork.
Because. Net framework's cookie is symmetric encryption, and. Net core is asymmetric encryption, it is necessary to intercept the default encryption and decryption operations of. Net core if you want to do it in. Net core. If possible, the best solution should be to port. Net framework's FormsAuthentication classes to. Net core. But looked at it with reflector, involved too much code, cut disorderly, github also did not find its source code, after a period of fuss finally feeling: concubine can not do (> wife <).
Related attributes of Cookie authentication
App.UseCookieAuthentication (new CookieAuthenticationOptions {AuthenticationScheme = "test", CookieName = "MyCookie", CookieDomain = "localhost", TicketDataFormat = new FormsAuthTicketDataFormat (")})
FormsAuthTicketDataFormat
Public class FormsAuthTicketDataFormat: ISecureDataFormat {private string _ authenticationScheme; public FormsAuthTicketDataFormat (string authenticationScheme) {_ authenticationScheme = authenticationScheme;} public AuthenticationTicket Unprotect (string protectedText, string purpose) {var formsAuthTicket = GetFormsAuthTicket (protectedText); var name = formsAuthTicket.Name; DateTime issueDate = formsAuthTicket.IssueDate; DateTime expiration = formsAuthTicket.Expiration; var claimsIdentity = new ClaimsIdentity (new Claim [] {new Claim (ClaimTypes.Name, name)}, "Basic"); var claimsPrincipal = new ClaimsPrincipal (claimsIdentity) Var authProperties = new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties {IssuedUtc = issueDate, ExpiresUtc = expiration}; var ticket = new AuthenticationTicket (claimsPrincipal, authProperties, _ authenticationScheme); return ticket;} FormsAuthTicket GetFormsAuthTicket (string cookie) {return DecryptCookie (cookie) .result;} async Task DecryptCookie (string cookie) {HttpClient _ httpClient = new HttpClient () Var response = await _ httpClient.GetAsync ("http://192.168.190.134/user/getMyTicket?cookie={cookie}"); response.EnsureSuccessStatusCode (); return await response.Content.ReadAsAsync ();}})
FormsAuthTicket
Public class FormsAuthTicket {public DateTime Expiration {get; set;} public DateTime IssueDate {get; set;} public string Name {get; set;}}
The above implements the decryption and interception of cookie, and then obtains the ticket from. Net framework through webapi.
[Route ("getMyTicket")] public IHttpActionResult GetMyTicket (string cookie) {var formsAuthTicket = FormsAuthentication.Decrypt (cookie); return Ok (new {formsAuthTicket.Name, formsAuthTicket.IssueDate, formsAuthTicket.Expiration);}
With the webapi line, the decryption is solved, and the encryption is even easier. There is only one step to get the encrypted cookie,.net core through webapi. Just save the cookie.
[HttpPost] public async Task Login (string name) {HttpClient _ httpClient = new HttpClient (); var response = await _ httpClient.GetAsync ($"http://192.168.190.134/user/getMyCookie?name={name}"); response.EnsureSuccessStatusCode (); string cookieValue = (await response.Content.ReadAsStringAsync ()) .trim ('\"); CookieOptions options = new CookieOptions (); options.Expires = DateTime.MaxValue; HttpContext.Response.Cookies.Append ("MyCookie", cookieValue, options); return RedirectToAction ("Index") }
Webapi gets cookie
[Route ("getMyCookie")] public string GetMyCookie (string name) {FormsAuthentication.SetAuthCookie (name, false); return FormsAuthentication.GetAuthCookie (name, false) .value;}
The rest of the code doesn't need to be changed, ok. Let's test it.
Ok, login is successful, and compatibility of. Net framework and. Net core authentication is completed.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.