How to modify .Aspnetcore.Identity.Application Cookie name? - asp.net-core

I wanna hide that i use ASP.NET Core.
The Cookie name show that i use ASP.NET Core and Identity.
So, I Would modify the Cookie name, I don't know way.
How to do this?
Somebody help me please.

I solved this.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "MyCustomCookieName";
});
}
}
This works since .NET Core 3.1.

When using AddMicrosoftIdentityWebAppAuthentication from Microsoft.Identity.Web in .Net 5+, the ConfigureApplicationCookie method didn't work for me. I was able to change the name of the .AspNetCore.Cookies cookie by using the following code placed directly after the AddMicrosoftIdentityWebAppAuthentication method call:
services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "AuthCookieName";
});

Related

NewtonsoftJsonInputFormatter is not available as InputFormatter in .NET5

I have NET5 application and in statup I have configured the application to use Newtonsoft instead of System.Text.Json. For posting CSP report I want to add application/csp-report as a supported media type.
Even though I have configured to use Newtonsoft using AddNewtonsoftJson, the NewtonsoftJsonInputFormatter is still not available as inputformatter. The following code returns null
when try to find in InputFormatters collection.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(config =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<NewtonsoftJsonInputFormatter>()
.First();
//jsonInputFormatter is null here
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report")
})
// Use Newtonsoft’s Json.NET instead of System.Text.Json.
.AddNewtonsoftJson((options)=>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
})
}
based on the post here . The accepted answer in that post did not work for me. However the other suggested work around by #Vincent Rutten did work
services.AddOptions<MvcOptions>()
.PostConfigure<IOptions<JsonOptions>, IOptions<MvcNewtonsoftJsonOptions>, ArrayPool<char>, ObjectPoolProvider, ILoggerFactory>(
(mvcOptions, jsonOpts, newtonJsonOpts, charPool, objectPoolProvider, loggerFactory) =>
{
var formatter = mvcOptions.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().First(i => i.SupportedMediaTypes.Contains("application/json"));
formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report"));
mvcOptions.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
mvcOptions.InputFormatters.Add(formatter);
});

Asp.Net Core configure Identity authentication middleware properly

Requirement is that I have MVC & WebAPI in the project. MVC views will be delivered for initial
rendering like Login, base views of features (ex:- Users/Index, Dashboard/Index etc..) Web APIs will be used for other work within these views via AJAX with JWT.
I am using Asp.Net core Identity for user management related work running on .Net 5.0
I am confused with configuring multiple identity schemes and the proper configuration of authentication/authorization pipeline in conigureservices() & configure() in startup.
To configure multiple auth schemes I referred to https://stackoverflow.com/a/64887479/2058413 since it's done using same versions that I use. So my startup methods are below which is similar to the code in that thread.
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("default");
services.AddDbContext<AppDBContext>(c => c.UseSqlServer(connectionString));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDBContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.LoginPath = "/Account/Login";
x.ExpireTimeSpan = TimeSpan.FromMinutes(10d);
x.AccessDeniedPath = "/Account/Register";
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123456")),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme);
defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
});
services.AddControllersWithViews();
}
My App configure method is below
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Then the test method in controller(where user should get redirected to after authentication) is below
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult Index()
{
return View();
}
To my understanding the order of the pipeline configuration is correct. Now here are the problems I face.
As specified in .AddCookie(option=>) , user doesn't get redirected to login page. However, if I remove the JwtBearerDefaults.AuthenticationScheme from the services.AddAuthorization(…) it gets redirected to login page properly. Why is that?
So I remove JwtBearerDefaults.AuthenticationScheme; which takes me to login and after successful login I can see that HttpContext.User.Identity.IsAuthenticated is set to true. But it doesn't redirect to Home/Index. No errors thrown and in browser console [network tab] it shows a 302 and redirect back to login. Since I have added [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] to Index method in HomeController, I tried removing the scheme and adding [Authorize] and tried again. Still it gets redirected to login page. This is another thing I am confused about.
So I removed everything related to dual scheme authentication and left the ConfigureService() with below code
string connectionString = Configuration.GetConnectionString("default");
services.AddDbContext<AppDBContext>(c => c.UseSqlServer(connectionString));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDBContext>();
services.AddControllersWithViews();
Now everything works fine (redirection to login if not authenticated and also redirects to /Home/Index after authorization).
I went through below links as well about multi scheme authentication, but I am still confused with this pipeline configuration.
ASP.NET Core WebAPI Cookie + JWT Authentication
https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2
https://mitchelsellers.com/blog/article/using-multiple-authentication-authorization-providers-in-asp-net-core
I need help only to this multi-scheme authentication pipeline configuration part.
Ok, after some research the main issue was;
I have mixed up old ways of registering services in StartUp (asp.net core 3.x). So had to clear up all those. Resources that helped me to do that;
Migrate from ASP.NET Core 3.1 to 5.0
ASP.NET Core Middleware
This cleaned up a lot of unnecessary code since in .Net 5 there were some shortcuts that could be used.
Order of service registrations. This may depend on what kind of services you are using, but in my case the order was something like below:
AddIdentity
setup Cookie & JWT authentication c)
My Multitenant stuff
AddCors
AddModules (will be option for some of you. I use it to load plugins dynamically)
Other stuff (However, even in these places the order might matter depending on
what you do)
The other thing was, I had to remove ConfigureApplicationCookie() since AddIdentity seems to be doing that. Also in AddAuthorization() earlier I had code to specify what are the default schemes i wanted to use (Cookie & JWT). But now I had to remove all that. Reason is Identity takes over the cookie scheme and when I specify below, JWTAuth takes over.
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Generally setting up Startup properly seems to be tricky depending on different services you use. Order will matter

How to localize LoginPath in ASP.NET Core MVC 3.1

I use CookieAuthentication in ASP.NET Core MVC 3.1 and I have to set the LoginPath while configuring in the Startup.cs.
I have this so far:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("CookieAuthentication")
.AddCookie("CookieAuthentication", config =>
{
config.Cookie.Name = "UserLoginCookie";
config.LoginPath = "/connexion";
config.SlidingExpiration = true;
config.ExpireTimeSpan = TimeSpan.FromHours(2);
});
...
}
But I would like now to be able to localize the LoginPath but I can't figure out how.
My goal is to call different Url according to the current culture. For example /connexion if the culture is French and /connect if it's English.
Any ideas how to achieve this??
Thank you!

Authorize attribute on entire project in .net mvc for security

I am applying authorize attibutes on each classes.
So is it possible to avoid this, and secure my entire web application at once?
Something like at "Namespace" level?
I am using .net core mvc application.
You should add your Authorization filter in ConfigureServices method on startup.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(YourCustomAuthorizationAttribute));
});
}
None of the above worked. But I got the solution. So following worked for me.
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
I know this may be late. But ideally, the check must happen only if there is an authorization header found. It is never possible for all pages in a project to require authentication... There must be at least one login page that does not need authentication

Is ApiExplorer supported in ASP.NET Core 1.0, and how to use it?

Does ASP.NET Core 1.0 support the use of APIExplorer? I'm unable to find any docs on it or how to use it, has anyone used it and can share some insight?
Itay's response helped me a bit getting the answer I wanted.
To anyone else that needs to use the ApiExplorer, Dr Rob Lang wrote an answer to How to get a list of all routes in ASP.NET Core?.
In brief, to get the routes you can have the IApiDescriptionGroupCollectionProvider injected into your controller using constructor injection. You then receive the routes in ApiDescriptionGroupCollectionProvider.ApiDescriptionGroups.Items. The routes will only be visible if you mark them as visible to ApiExplorer. This can be done per controller or by using a convention. Since I want to use it on all of my controllers, I used an IApplicationModelConvention:
public class ApiExplorerVisibilityEnabledConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
foreach (var controller in application.Controllers)
{
if (controller.ApiExplorer.IsVisible == null)
{
controller.ApiExplorer.IsVisible = true;
controller.ApiExplorer.GroupName = controller.ControllerName;
}
}
}
}
Then in Startup.cs, you add the convention:
public void ConfigureServices(IServiceCollection services)
{
// other calls omitted for brevity
services.AddMvc(opt =>
{
opt.Conventions.Add(new ApiExplorerVisibilityEnabledConvention());
});
}
Code from How to get a list of all routes in ASP.NET Core? - Dr Rob Lang, Mar 2 '16 at 14:40
There's a downloadable NuGet of the ApiExplorer for ASP.NET Core: Microsoft.AspNetCore.Mvc.ApiExplorer 1.0.0
So this means that it's supported (used by Swagger/Swashbackle which are also supported AFAIK).