I am trying to implement google authentication in asp.net 5 and getting error
Exception: The oauth state was missing or invalid.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ManualDataMiningManagerContext>(
options => options.UseSqlServer("name=ConnectionStrings:DBconnection"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ManualDataMiningManagerContext>()
.AddDefaultTokenProviders();
services.AddRazorPages();
services.AddControllersWithViews();
services.AddAuthentication()
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection =
Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
options.SignInScheme = IdentityConstants.ExternalScheme;
});
services.ConfigureExternalCookie(options => { options.Cookie.SameSite = SameSiteMode.None; });
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseForwardedHeaders();
app.UseHsts();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseForwardedHeaders();
//The default HSTS value is 30 days.You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapDefaultControllerRoute();
});
}
my startup class method attached. am I missing anything?
and one more thing this app deployed on subdomain looks like operation-done.abc.com
Related
I'm experiencing some difficulties with CORS in angular 11 and Asp.net Core 2.1.1. The Angular server running on port 4201, the Asp.net Core server on port 8990. I always get an error like this
Access to XMLHttpRequest at 'http://10.31.80.108:8990/api/localization/login' from origin 'http://10.31.80.108:4201' 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.
although I have enabled CORS in the Startup.cs file:
app.UseCors(builder => builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins(new []{ "http://10.31.80.108", "http://10.31.80.108:4201"})
//.WithOrigins(origins.ToArray())
.AllowCredentials());
I've tried different variations that should allow all requests, but it doesn't work in Angular. Can anyone suggest a possible solution?
Here is most of the Startup file:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
...
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMemoryCache();
// services.AddCors();
services.AddCors(o => o.AddPolicy("AllowAnyOrigin", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
})); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(Configuration["CultureOptions:DefaultCulture"]);
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(Configuration["CultureOptions:DefaultCulture"]);
var cultureOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(new CultureInfo(Configuration["CultureOptions:DefaultCulture"])),
};
var configCultures = Configuration.GetSection("CultureOptions:SupportedCultures").GetChildren();
configCultures.ForEach(config =>
{
cultureOptions.SupportedCultures.Add(new CultureInfo(config.Value));
cultureOptions.SupportedUICultures.Add(new CultureInfo(config.Value));
});
app.UseRequestLocalization(cultureOptions);
List<string> origins = Configuration.GetSection("Origins:value").Get<List<string>>();
app.UseCors("AllowAnyOrigin");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// https://joonasw.net/view/hsts-in-aspnet-core
app.UseHsts();
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
});
}
you have a wrong syntax. try this
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
app.UseRouting();
app.UseCors("AllowAnyOrigins");
//app.UseAuthorization();
}
if it works replace AllowAnyOrigin() with yours
.WithOrigins ("http://10.31.80.108", "http://10.31.80.108:4201");
I have created an api using .net core 5.0 but no matter what I do it seems to block my request to it giving the error
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my code in my startup.cs is
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});
services.AddTransient<IChatLog, LogsData>(provider => new LogsData());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
From what I have read that should allow any requests from anywhere, but for some reason it is still blocking.
Has anyone any idea what is wrong?
Because app.UseCors() did not specify a policy name. You can add the name AllowAnyCorsPolicy.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseCors("AllowAnyCorsPolicy");
//...
}
Use this syntax:
services.AddCors(o => o.AddPolicy("AllowAnyCorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
and this too:
app.UseCors("AllowAnyCorsPolicy");
I have an interesting problem and Microsoft's documentation doesn't seem to cover it. I am creating an ASP.NET Core 3.1 project and using authorization through the app, so you have to have permission to view the page, or some pages you just need to be logged into the application to access the page. That is all working correctly if you are logged in.
However with the Identity Area's they introduced on a user that is not logged in it redirects the user to: (If I manually add in /Identity/ it behaves normally.
"/Login/returnurl=something?something"
instead of
"/Identity/Login/returnUrl=something?something
Here is the startup file:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<DataProtectionTokenProviderOptions>(o =>
o.TokenLifespan = TimeSpan.FromHours(3));
services.AddTransient<IEmailSender, EmailSender>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
//These keys need to be setup on Azure or where you are running it to make it work.
//services.AddAuthentication()
//.AddFacebook(facebookOptions =>
//{
// facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
// facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
//})
//.AddGoogle(options =>
//{
// IConfigurationSection googleAuthNSection =
// Configuration.GetSection("Authentication:Google");
// options.ClientId = googleAuthNSection["ClientId"];
// options.ClientSecret = googleAuthNSection["ClientSecret"];
//});
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
app.UseMvc();
}
I have just resolved the same problem adding these lines to the ConfigureServices.
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
I'm recently migrated from ASP .NET Core 2.2 to 3.1, everything works fine but I have an issue with ignoring authorization on Dev environment.
The code that I used in CORE 2.2:
if (env.IsDevelopment())
{
//On Development - ignore authorization
services.AddMvc(opts => { opts.Filters.Add(new AllowAnonymousFilter()); })
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
else
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
This obviously doesn't work on CORE 3.1 but I can't find any equivalent code that works.
Among other things, I tried to use this code (below) with no result.
services.AddControllers(opts =>
{
if (env.IsDevelopment())
{
opts.Filters.Add(new AllowAnonymousFilter());
}
else
{
}
});
Please help me with this.
My relevant code (CORE 3.1):
public void InstallServices(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, ILogger logger)
{
services.AddControllers(opts =>
{
if (env.IsDevelopment())
{
opts.Filters.Add(new AllowAnonymousFilter());
}
else
{
}
});
services.AddAutoMapper(typeof(Startup));
var jwtSettings = new JwtSettings();
configuration.Bind(nameof(JwtSettings), jwtSettings);
services.AddSingleton(jwtSettings);
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = jwtSettings.PrivateSigningSecretKey,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddSingleton(tokenValidationParameters);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = tokenValidationParameters;
});
services.AddAuthorization(options =>
{
options.AddPolicy(Authorizations.RequireAdminOrManagerRole,
policy => policy.RequireRole(Authorizations.Admin, Authorizations.Manager));
});
//deleted Swagger setup
}
public void InstallConfiguration(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, ILogger logger)
{
//deleted Swagger setup
app.UseHttpsRedirection();
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
I found something that works for me.
Let me know if you have a better solution
My Configuration:
app.UseHttpsRedirection();
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseRouting();
if (env.IsStaging() || env.IsDevelopment())
{
//on staging/development dont require authentication
app.Use(async (context, next) =>
{
// Set claims for the test user.
var claims = new[] { new Claim("role", "Admin"), new Claim("sub", "some guid") };
var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
// Add the test user as Identity.
context.User.AddIdentity(id);
// User is now authenticated.
await next.Invoke();
});
}
else
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
Credit:
Programmatically add [AllowAnonymous] attribute to all my controller methods
Hello I'm trying to migrate a .Net Framework 4.6 application to asp.net core 2.2 and I'm block on the HttpContext.Session use.
I can call the SetString method, but on the second request the GetString return always null value.
I tried different answers found on Stackoverflow and official documentation but none of them are working on my case
public void ConfigureServices(IServiceCollection services)
{
var appConfiguration = new AppConfigurationManager(Configuration);
var allowedOrigins = appConfiguration.AllowedOrigins.Split(',').Select(s => s.Trim()).ToArray();
services.AddSingleton(Configuration); // Config
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
})); // CORS
TokenVerifier.ControlToken(services, "secretToken");
services.AddSignalR();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
options.Cookie.Name = "MySession";
options.IdleTimeout = TimeSpan.FromDays(1);
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("default");
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<MindHub>("/myapp");
});
app.UseMiddleware<ExceptionMiddleware>();
app.UseSession();
app.UseMvc();
}
Note that JWT Authentication, CORS and Signalr are working (maybe helpfull for some of you)
Here is my final working sample code maybe usefull for some of you.
Note than the order is very important.
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
string[] allowedOrigins = new string[]; // put your allowed origins here
services.AddSingleton(Configuration); // Config
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
TokenVerifier.ControlToken(services, "secretToken");
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = long.MaxValue; // In case of multipart
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // HttpContext into ASP.NET Core
// Register your stuff here
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("default");
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<YourHub>("/hubName");
});
app.UseMiddleware<ExceptionMiddleware>();
app.UseHttpsRedirection();
app.UseMvc();
}