synercoder / formsauthentication Goto Github PK
View Code? Open in Web Editor NEWEnable ASP.NET Core 2 cookies to read old ASP.NET Forms Authentication cookies
License: MIT License
Enable ASP.NET Core 2 cookies to read old ASP.NET Forms Authentication cookies
License: MIT License
We have a legacy ASP.NET Application that also specifies the purpose parameter during encoding:
MachineKey.Protect(bytes, purpose1, purpose2);
Reference source signature:
public static byte[] Unprotect(byte[] protectedData, params string[] purposes)
But your library does not implement the handling of the purposes during decryption:
var cryptoProvider = AspNetCryptoServiceProvider.GetCryptoServiceProvider(_options);
var cryptoService = cryptoProvider.GetCryptoService();
byte[] unprotectedData = cryptoService.Unprotect(bytes);
There is no purpose / purposes parameter available to apply.
Hello,
I need to do this, however, our ASP.Net 4.5 is using both a custom ticket Version. However, your serializer.deserializer (FormsAuthenticationCryptor's ConvertToBytes hardcodes it to 1 and ConvertToAuthenticationTicket ignores it) does not support this.
Is it something you would consider adding? I don't think it would be a major change. I would be ready to provide a PR.
I ran your samples from Visual Studio 2019, while they worked with IIS Express. But when I deployed them on IIS on my local machine, decryption in .Net core application seems to be failing - "Error occurred during a cryptographic operation.".
This part seems to be returning null
if (!CryptoUtil.BuffersAreEqual(
buffer1: protectedData, buffer1Offset: ivByteCount + encryptedPayloadByteCount, buffer1Count: signatureByteCount,
buffer2: computedSignature, buffer2Offset: 0, buffer2Count: computedSignature.Length))
{
// the computed signature didn't match the incoming signature, which is a sign of payload tampering
return null;
}
When I compared cookie generated from IIS Express and IIS, they are of different length. Could that be a problem?
One other thing I have is - I have machine keys generated on IIS which are same as what I'm using in IIS Express, basically, I'm using same keys as in repo samples. Any clue about why it doesn't work on IIS?
Hi there ๐
First, I want to thank you for this great piece of code.
I've come across it and it works like a charm!
Now, one issue that I've encountered is that when the value of a cookie can't be decrypted, it throws a CryptographicException
that is not handled and bubbles up the stack, which crashes the request.
Would you be open to catching exceptions in FormsAuthenticationDataFormat<TData>.Unprotect
and return default(TData)
on exceptions like it's done in the SecureDataFormat<TData>
in ASP.NET Core?
If so, we could also augment the FormsAuthenticationOptions
with a property that specifies what to do with the exceptions, like logging, etc...
Let me know what you think, I'll be happy to open a PR if you give me the green light.
Cheers!
I am trying to create the forms authentication cookie in a .net core web app which works. When I redirect to a web forms project I get an error when trying to decrypt the cookie using system.web.security.formsauthentication.Decrypt. The machine key matches except that the web forms project has the encryption method set to auto but changing it does not fix the problem.
I'm trying to integrate this into a .Net Core 3.1 app so it can accept a forms authentication cookie from a legacy .Net 4.5 web app. I believe I've set things up properly in ConfigureServices()
(excerpt below). All configuration values including the cookie name and encryption/decryption keys and methods match the .Net 4.5 app.
However, when I access an [Authorize]
protected controller action, none of the Synercoding.FormsAuthentication
or FormsAuthHelper
code is called to validate the existing authentication cookie created by the .Net 4.5 web app. Tracing into the .Net Core code, I see that in the Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke()
method, var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource: endpoint);
always returns authorizeResult.Challenged
. (Unfortunately, I cannot step into the AuthorizeAsync()
method itself to inspect its processing.) The context.ChallengeAsync()
method tries to redirect to the login page (which doesn't exist), but in the process of trying to set up that redirect, the FormsAuthenticationDataFormat()
constructor is called, and the set
method of the Microsoft.AspNetCore.Http.CookieBuilder.Name
property is called with the "MyAuthCookie"
configuration value -- so I see the configuration kicking in at that point. (The Microsoft.AspNetCore.Http.CookieBuilder.Name
get
method is called shortly thereafter, returning "MyAuthCookie"
).
I'm puzzled why none of the Synercoding.FormsAuthentication
code is called to try to validate the existing cookie before trying to redirect to the login page. I can see that the "MyAuthCookie"
.Net 4.5 authentication cookie does exist in the HttpContext
object with the value generated by the .Net 4.5 app.
Any suggestions for how to debug or troubleshoot the configuration would be very welcome.
Here's the ConfigureServices()
excerpt:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Synercoding.FormsAuthentication;
// ...stuff omitted...
// ...in ConfigureServices()...
var formsAuthConfig = Configuration.GetSection("FormsAuthentication");
var formsAuthOptions = new FormsAuthenticationOptions()
{
DecryptionKey = formsAuthConfig.GetValue<string>("DecryptionKey"),
ValidationKey = formsAuthConfig.GetValue<string>("ValidationKey"),
EncryptionMethod = formsAuthConfig.GetValue<EncryptionMethod>("EncryptionMethod"),
ValidationMethod = formsAuthConfig.GetValue<ValidationMethod>("ValidationMethod"),
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.Name = "MyAuthCookie";
options.AccessDeniedPath = formsAuthConfig.GetValue<string>("AccessDeniedPath");
options.LoginPath = formsAuthConfig.GetValue<string>("LoginPath");
options.ReturnUrlParameter = formsAuthConfig.GetValue<string>("ReturnUrlParameter");
options.TicketDataFormat = new FormsAuthenticationDataFormat<AuthenticationTicket>(
formsAuthOptions,
FormsAuthHelper.ConvertCookieToTicket,
FormsAuthHelper.ConvertTicketToCookie
);
});
I have been trying to integrate the component to my solution but it doesnt call the ConvertCookieToTicket method, in the sample project it works fine, but for some reason I cant identify it doesnt work when using my own login app in spite it seems to be configured just like the one you included in your sample, you can find my test proyecto in this link:
https://www.dropbox.com/s/j9t1vi3gp9go582/FormsAuthentication-update-netcore-3.rar?dl=0
When running the solution try using this login: http://localhost:58499/
Any clue of what could be missing or wrong, thank you very much for your time and help
Hi,
We had a authserver which serves FedAuth token for existing .Net framework projects.
Now We are .net core web project for Integrate auth server.Is there any solution for that ?
Regards,
Hi,
In my situation, I have a new ASP.NET Core application which needs to generate a Cookie in order to use against an ASP.NET 4 application (not reading a Cookie from ASP.NET 4). I tried the sample setup you have provided in my ASP.NET Core Startup.cs, which appears to generate a Cookie (which I thought would now be a traditional ASP.NET 4 Cookie using MachineKey in AppSettngs.json). But when I tried to use it against the ASP.NET 4 application, it appears to not work. Maybe my assumption is wrong.
What I'd rather do is keep my original setup in ASP.NET Core (using JwtBearer Token) and then within my API controller, generate a valid Forms Auth Cookie for ASP.NET 4. But not really sure how to accomplish this with the library. Is this possible? This is how my legacy code worked in original ASP.NET 4 code:
HttpCookie httpCookie = FormsAuthentication.GetAuthCookie(this.UserName, true);
I then added this Cookie to the WebRequest object when making a call to the other Web Application. I've migrated my legacy ASP.NET 4 application to ASP.NET Core but still need to communicate to another ASP.NET 4 application. User's always log into my ASP.NET Core application, so this is where all the Cookie information be created from.
As always, any help would be appreciated.
Thanks,
Devaron
Hi,
I have two apps web apps (first is .net 4.5 and second one is .net core 2). I want to share cookie that is set in first one and to read it in second one.
I keep getting CryptographicException for some reason... I tried your example and every thing works as expected. Can you please point me in right direction to try to find solution for my problem?
Here are my configurations:
.net 4.5
<machineKey
validationKey="F2D27DF0348E9A3EAD6AC66330C31F821394D4CD1A5E139EEE85EA9D9F2A963E55EC87572F699FB834292CC9E37AD56B6B26AA379106CBA5E9AA544C688F3E92"
decryptionKey="F6D5A5C8DDEC57481610829F58D6C95BDAC5FA21082F3FA9CB5A36DCEAACBEDB" validation="SHA1"
decryption="AES"
/>
<compilation targetFramework="4.5" debug="true" />
<authentication mode="Forms">
<forms name=".ezesuite" protection="All" loginUrl="~/Account/Login" timeout="1440" requireSSL="false" slidingExpiration="true" ticketCompatibilityMode="Framework40" path="/" domain="" />
</authentication>
.net core 2
"FormsAuthentication": {
"CookieName": ".ezesuite",
"BaseAuthUrl": "http://mysite.staging.com",
"DecryptionKey": "F6D5A5C8DDEC57481610829F58D6C95BDAC5FA21082F3FA9CB5A36DCEAACBEDB",
"ValidationKey": "F2D27DF0348E9A3EAD6AC66330C31F821394D4CD1A5E139EEE85EA9D9F2A963E55EC87572F699FB834292CC9E37AD56B6B26AA379106CBA5E9AA544C688F3E92",
"EncryptionMethod": "AES",
"ValidationMethod": "SHA1"
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.