Claimtransformation not working after upgrading System.IdentityModel.Tokens.Jwt - c#

I am upgrading System.IdentityModel.Tokens.Jwt in a asp.net fw472 web api solution and using Swagger for testing purposes.
When I upgrade the package to a higher version than 3.0.2, principal.Identity does not contain the jwt token information as it used to before upgrading. The authenticationType property is also empty string instead of 'JWT' and there is only one claim in the list of claims. This is how the claimtransformation is used in the startup.cs.
app.UseClaimsTransformation(principal =>
{
if (!principal.Identity.IsAuthenticated)
{
return Task.FromResult(principal);
}
// do something else when authenticated..
}
Do I need to change something additionally in code when upgrading from version 3.0.2 to 5.0.3 ?

Related

AzureADB2CDefaults obsolete, how do I replace it?

I'm in the process of updating some nuget packages and noticed that AzureADB2CDefaults has been made obsolete. I know that Microsoft.Identity.UI has incorporated AzureADB2C into it but I'm unsure how to use it whilst still referencing AzureADB2C, the code below is whats causing this warning:
services.AddAuthentication(
options =>
{
options.DefaultScheme = AzureADB2CDefaults.AuthenticationScheme;
})
I've tried setting DefaultScheme to just a string of "AzureADB2"
I've also tried adding:
.AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"),
Constants.AzureAdB2C, null);
but not having much luck.
Is there any way to reference azure active directory with microsoft identity? Any suggestions on how to replace this bit of code would be much appreciated
Note that: Microsoft.AspNetCore.Authentication.AzureADB2C.UI
Nuget package is obsolete and Microsoft advises to use the
Microsoft.Identity.Web package.
To resolve the issue, install the Latest version of Microsoft.Identity.Web and Microsoft.Identity.Web.UI.
In the startup.cs file replace the below code:
services.AddAuthentication(
options =>
{
options.DefaultScheme = AzureADB2CDefaults.AuthenticationScheme;
})
with
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureADB2C"));
and instead of using services.AddRazorPages(); replace it with services.AddRazorPages().AddMicrosoftIdentityUI();
And also make changes in code by referring to this blog by Andreas Helland.
After making the changes, the code will execute successfully:
For more in detail, refer below links:
Migrating Azure AD B2C integration going from .NET Core 3.1 to .NET 5 by Andreas Helland
Azureb2c login is not connecting to account controller by killswitch

AuthenticationBuilder does not contain a definition for "AddMicrosoftIdentityWebApp"

In the startup.cs file, I tried the following lines to connect the Azure AD B2C into my .Net Core 5 Web-API project followed from a GitHub Repo Here. But it's not accepting the AddMicrosoftIdentityWebApp predefined method in my .Net Core 5+ React template project. Where did I go wrong?
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));
I have tried with OpenId scheme and the following method as well.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));
I haven't installed the below-given package!.
Microsoft.Identity.Web;

AddSignIn Method Missing In ASP.NET Core 2.1

I created an ASP.NET Core web application and I tried to add the following code for implementing authentication but the AddSignIn method could not be found.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddSignIn("AzureAdB2C", Configuration, // This method is missing
options => Configuration.Bind("AzureAdB2C", options));
I am using the Microsoft.AspNetCore.Authentication.OpenIdConnect package so I'm not sure what I'm missing here.
AddSignIn is in the namespace Microsoft.Identity.Web, which is in the package of the same name.
Have you installed the package? https://www.nuget.org/packages/Microsoft.Identity.Web

How to set SameSite cookie attribute to explicit None ASP NET Core

Chrome 76 will begin to support an explicit SameSite: None attribute
https://web.dev/samesite-cookies-explained/
I found that the current implementation of ASP.NET Core treats SameSiteMode.None as a no-op and does not send any attribute. How can I add a custom attribute to a cookie and thereby add an explicit SameSite: None to the cookie text?
Appending the attribute to the cookie value does not work as HttpResponse.Cookies.Append url-encodes the cookie value.
Same issue occurs in ASP.NET as in ASP.NET Core.
Until Microsoft produce a fix, a hack that's working for me is to replace
myCookie.Path = "/";
myCookie.SameSite = SameSiteMode.None; // has no effect
with
myCookie.Path = "/; SameSite=None";
This adds SameSite=None to the set-cookie header in the HTTP response.
It's now fixed in latest release of all versions of .NET Framework and .NET Core (https://github.com/aspnet/AspNetCore/issues/12125)
I have multiple projects running on .NET Core 2.2 and after upgrading to 2.2.207, I don't have the problem anymore.
Here a sample code present in ConfigureServices method of Startup.cs file
services.ConfigureApplicationCookie(options => {
options.Cookie.SameSite = SameSiteMode.None;
});
[Edit]
If you are using all dlls and packages from nuget,
you have to ensure Microsoft.Net.Http.Headers is in version 2.2.8 of above.
After last KB from microsoft in 10 december 2019,
It should be fixed in .net framework and dotnetcore.
see:
https://learn.microsoft.com/en-us/aspnet/samesite/system-web-samesite
https://learn.microsoft.com/en-us/aspnet/samesite/kbs-samesite
response.Headers.Append("set-Cookie", $"{cookieName}={cookieValue}; path=/; SameSite=None; Secure"); seems to work as expected.
I tested this by enabling same-site-by-default-cookies and cookies-without-same-site-must-be-secure in Chrome Dev 76
Other answers have mentioned .Net Core fix, so I skip that part.
The .Net Framework fix is provided via a "Quality Rollup".
Here's the KB for .Net 4.8.
Here's the KB for .Net 4.7.2.
Here's the relevant MSDN source.

Unable to configure 'IApplicationBuilder UseOwin'

As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.
I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.
Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.
Note:
I am using dotnetcore 2.0 with Visual Studio 2017
Error
I am getting following error.
return owinAppBuilder.Build,
Task>>(); TypeLoadException: Could not load type
'System.Security.Cryptography.DpapiDataProtector' from assembly
'System.Security, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
My attempt
app.UseOwin(setup => setup(next =>
{
var owinAppBuilder = new AppBuilder();
var aspNetCoreLifetime =
(IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
new AppProperties(owinAppBuilder.Properties)
{
OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
DefaultApp = next,
AppName = "test"
};
// Only required if CORS is used, configure it as you wish
var corsPolicy = new System.Web.Cors.CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = true
};
//corsPolicy.GetType()
// .GetProperty(nameof(corsPolicy.ExposedHeaders))
// .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());
owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
PublicClientId = "self";
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
Provider = new MyServiceProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true,
RefreshTokenProvider = new MyRefreshTokenProvider(),
};
owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
//owinAppBuilder.UseTus(context => new DefaultTusConfiguration
//{
// // Excluded for brevity, use the same configuration as you would normally do
//});
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:
Package 'Microsoft.Owin 3.1.0' was restored using
'.NETFramework,Version=v4.6.1' instead of the project target framework
'.NETCoreApp,Version=v2.0'. This package may not be fully compatible
with your project.
There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).
So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.
If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change
<TargetFramework>netcoreapp2.0</TargetFramework>
To some .NET framework version that supports .NET Standard 2.0, for example:
<TargetFramework>net47</TargetFramework>
Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.
That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.
Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).
The Microsoft.Owin components will not work on dotnet core 2.0, they only work on .NET 4.5+

Categories

Resources