I would like to change the default Cookie name for .AspNetCore.Antiforgery.xxx in ASP.NET Core 3.X MVC, however I do not seem to find any documentation on it. Is it even possible?
The only one I found to be able to alter was this:
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
options.ConsentCookie.Name = "GDRP";
});
This is achievable using AddAntiforgery. Here's an example taken from the docs and modified accordingly:
services.AddAntiforgery(options =>
{
options.Cookie.Name = "YourCookieName";
});
There's a useful page in the docs that lists the built-in ASP.NET Core cookies and where the configuration for each comes from.
For .NET 5.0 and higher
in ProjectRoot/Startup.cs class
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "your_cookie_name";
});
// ...
services.AddControllers();
}
ok, found it already, for those that are looking
services.AddAntiforgery(options =>
{
options.Cookie.Name = "my-x-name";
options.HeaderName = "my-x-name";
});
It will accept any string, need to validate if it works or if something else needs to be updated...
Related
I used the accepted answer to How to check user-agent in ASP.NET Core health check calls (MapHealthChecks)? , with one difference in requirement:
My application is not using App services authentication and authorization. Therefore, I needed to allow anonymous access for healthcheck as per documentation.
Here are changes to Startup.cs
//other services
services.AddHttpContextAccessor();
services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();
services.AddHealthChecks()
.AddCheck<HealthCheckFoo>("health_check_foo")
.AddCheck<HealthCheckBar>("health_check_bar");
//other services.AddAuthorization
services.AddAuthorization(options =>
{
options.AddPolicy("HealthCheckPolicy", builder =>
{
builder.AddRequirements(new UserAgentRequirement("HealthCheck/1.0"));
});
});
//...
app.UseEndpoints(endpoints =>
{
//other endpoints...
endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
.RequireAuthorization("HealthCheckPolicy");
.WithMetadata(new AllowAnonymousAttribute());
My expectation is that when testing locally, https://localhost:5001/health return an error. It does not.
It looks as your startup class has a mistake on the endpoints.MapHealthChecks adds a RequireAuthorization but as the same time you also add the AllowAnonymousAttribute.
Try with:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health", new HealthCheckOptions()
{
AllowCachingResponses = false,
})
.RequireAuthorization("HealthCheckPolicy");
});
I'm trying OpenIddict 3.0. I followed the steps in the documentation, created an Authorize controller, and added a test application. When I try to run I get this exception:
The OpenIddict ASP.NET Core server cannot be used as the default
scheme handler. Make sure that neither DefaultAuthenticateScheme,
DefaultChallengeScheme, DefaultForbidScheme, DefaultSignInScheme,
DefaultSignOutScheme nor DefaultScheme point to an instance of the
OpenIddict ASP.NET Core server handler
I cannot find what I'm doing wrong.
Here is my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
// Configure the context to use Microsoft SQL Server.
options.UseInMemoryDatabase("Identity");
// Register the entity sets needed by OpenIddict.
// Note: use the generic overload if you need
// to replace the default OpenIddict entities.
options.UseOpenIddict<Guid>();
});
AddIdentityCoreServices(services);
services.AddOpenIddict()
// Register the OpenIddict core components.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>()
.ReplaceDefaultEntities<Guid>();
})
// Register the OpenIddict server components.
.AddServer(options =>
{
// Enable the token endpoint (required to use the password flow).
options.SetTokenEndpointUris("/connect/token");
// Allow client applications to use the grant_type=password flow.
options.AllowPasswordFlow();
// Mark the "email", "profile" and "roles" scopes as supported scopes.
//options.RegisterScopes(OpenIddictConstants.Scopes.Email,
// OpenIddictConstants.Scopes.Profile,
// OpenIddictConstants.Scopes.Roles);
// Accept requests sent by unknown clients (i.e that don't send a client_id).
// When this option is not used, a client registration must be
// created for each client using IOpenIddictApplicationManager.
options.AcceptAnonymousClients();
// Register the signing and encryption credentials.
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
// Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough() // Add this line.
.EnableTokenEndpointPassthrough()
.DisableTransportSecurityRequirement(); // During development, you can disable the HTTPS requirement.
})
// Register the OpenIddict validation components.
.AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the ASP.NET Core host.
options.UseAspNetCore();
});
// ASP.NET Core Identity should use the same claim names as OpenIddict
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
private static void AddIdentityCoreServices(IServiceCollection services)
{
var builder = services.AddIdentityCore<ApplicationUser>();
builder = new IdentityBuilder(
builder.UserType,
typeof(ApplicationRole),
builder.Services);
builder.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddSignInManager<SignInManager<ApplicationUser>>();
}
Please assist me on what I'm doing wrong.
I finally figured out where I went wrong. #Train Thanks for pointing me in the right direction.
changing the services.AddAuthentication(...) from
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
});
to
services.AddAuthentication(options =>
{
options.DefaultScheme = OpenIddict.Validation.AspNetCore.OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
});
What's you're method of authentication? Cookie? JWT?
You need to change this line of code. You can't set OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; as the default scheme
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
});
Default Authentication Scheme
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
or overload
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
});
Here are the docs on Authentication with a lot more to read up on.
I've been trying to set up Discord Oauth2 token authentication on an ASP.NET Core 2.2 / Angular 7 project and it has been quite a bumpy ride.
I'm using this
I really can't seem to find any examples that give more than a fraction of the explanation required to set this all up. The error I'm currently battling with is the following:
Access to XMLHttpRequest at 'https://discordapp.com/oauth2/authorize?client_id=<removed>&scope=identify&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fsignin-discord&state=<removed>'
(redirected from 'http://localhost:5000/api/v1/Authentication/SignIn') from origin 'http://localhost:5000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
For context, here is some of my code:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader());
});
...
services.AddAuthentication(options =>
{
options.DefaultScheme = DiscordAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = DiscordAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/signout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
options.SlidingExpiration = true;
})
.AddDiscord(options =>
{
options.ClientId = "<removed>";
options.ClientSecret = "<removed>";
options.Scope.Add("identify");
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseCors("AllowAll");
...
}
// in AuthenticationController.cs
public class AuthenticationController : Controller
{
[HttpPost("[action]")]
public IActionResult SignIn()
{
return Challenge(new AuthenticationProperties {RedirectUri = "http://localhost:5000"});
}
...
}
What i've been trying
I tried following this
I tried all of these combinations of services.addCors() and app.UseCors() to no avail
services.AddCors();
app.UseCors(builder =>
builder.WithOrigins("http://localhost:5000").AllowAnyHeader());
services.AddCors();
app.UseCors(builder =>
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
and everything inbetween. The error does not change no matter what I do with cors. Also, yes I have the Microsoft.AspNetCore.Cors nu-get package installed. Yes, app.UseCors() is called before app.useMvc
Any other ideas?
I experienced a similar issue today but figured it out later. Make sure you are using the same versions of net core. I happened to be using both 2.1 and 2.2 packages.
I'm trying to use Ocelot with IS4 following
https://ocelot.readthedocs.io/en/latest/features/authentication.html
When using
public void ConfigureServices(IServiceCollection services)
{
var authenticationProviderKey = "TestKey";
services.AddAuthentication()
.AddJwtBearer(authenticationProviderKey, x =>
{
});
}
and use "TestKey" in ocelot.json, it throws an error when starting the application
Unable to start Ocelot, errors are: TestKey,AllowedScopes:[] is unsupported authentication provider
Any idea what's wrong? Do I need set up something in particular in my IdentityServer app?
You need to add the options, e.g.:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// base-address of your identityserver
options.Authority = "https://demo.identityserver.io";
// name of the API resource
options.Audience = "api1";
});
More info at: http://docs.identityserver.io/en/latest/topics/apis.html#
You will also need to add an API resource to your Identity Server:
new ApiResource("api1", "Some API 1")
See:
http://docs.identityserver.io/en/latest/topics/resources.html and http://docs.identityserver.io/en/latest/reference/api_resource.html#refapiresource
I'm creating an ASP.NET 5 MVC 6 app that will use Facebook/Google authentication only. I'm also trying to use the cookie middleware without the whole ASP.NET Identity -- following this article:
https://docs.asp.net/en/latest/security/authentication/cookie.html
So I started with an blank app with no authentication then added the Microsoft.AspNet.Authentication.Cookies and Microsoft.AspNet.Authentication.Facebook NuGet packages in order to have a very minimalistic approach where I don't include anything that I don't need.
I added the following code into Configure in Startup.cs but I'm getting "SignInScheme option must be provided" error. Any idea what I'm missing?
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "MyCookieMiddlewareInstance";
options.LoginPath = new PathString("/Accounts/Login/");
options.AccessDeniedPath = new PathString("/Error/Unauthorized/");
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});
app.UseFacebookAuthentication(options =>
{
options.AppId = "myFacebookAppIdGoesHere";
options.AppSecret = "myFacebookAppSecretGoesHere";
});
As indicated by the error message you're seeing, you need to set options.SignInScheme in your Facebook middleware options:
app.UseFacebookAuthentication(options => {
options.AppId = "myFacebookAppIdGoesHere";
options.AppSecret = "myFacebookAppSecretGoesHere";
// This value must correspond to the instance of the cookie
// middleware used to create the authentication cookie.
options.SignInScheme = "MyCookieMiddlewareInstance";
});
Alternatively, you can also set it globally from ConfigureServices (it will configure every authentication middleware so you don't have to set options.SignInScheme):
public void ConfigureServices(IServiceCollection services) {
services.AddAuthentication(options => {
// This value must correspond to the instance of the cookie
// middleware used to create the authentication cookie.
options.SignInScheme = "MyCookieMiddlewareInstance";
});
}