i have create asp net core project
but in client side some times he get bad request long term ,
and some Times some Function Not Work Correctly and it save Some Data and Discard other
but it solved only when he clear Cookies From Browser
so i tried to Run Software in another PC but Also Problem Exist
he should Clear Cookies From Browser
So is there any Solution For this Problem To Clear Cookies Automatic in Code?
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(option =>
{
option.IdleTimeout = TimeSpan.FromMinutes(10);
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SameSite = SameSiteMode.Strict;
});
services.Configure<IdentityOptions>(option =>
{
option.Password.RequiredLength = 6;
option.Password.RequireUppercase = false;
option.Password.RequireNonAlphanumeric = false;
option.Password.RequireLowercase = false;
});
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter());
});
services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme,
options =>
{
options.LoginPath = "/Accounting/Login";
options.LogoutPath = "/Accounting/Logout";
options.AccessDeniedPath = "/Accounting/AccessDenied";
options.SlidingExpiration = true;
});
services.AddAuthorizationCore(
options =>
{
//options.AddPolicy("UsersEdit",
// policy => policy.RequireAssertion(
// context =>context.User.HasClaim());
// users policy
options.AddPolicy("UsersShow",
policy => policy.RequireClaim("UsersShow", "true"));
options.AddPolicy("UsersAdd",
policy => policy.RequireClaim("UsersAdd", "true"));
options.AddPolicy("UsersEdit",
policy => policy.RequireClaim("UsersEdit", "true"));
options.AddPolicy("UsersDelete",
policy => policy.RequireClaim("UsersDelete", "true"));
// role policy
options.AddPolicy("RoleShow",
policy => policy.RequireClaim("RoleShow", "true"));
options.AddPolicy("RoleAdd",
policy => policy.RequireClaim("RoleAdd", "true"));
options.AddPolicy("RoleEdit",
policy => policy.RequireClaim("RoleEdit", "true"));
options.AddPolicy("RoleDelete",
policy => policy.RequireClaim("RoleDelete", "true"));
// Stock
options.AddPolicy("StockShow",
policy => policy.RequireClaim("StockShow", "true"));
options.AddPolicy("StockAdd",
policy => policy.RequireClaim("StockAdd", "true"));
options.AddPolicy("StockEdit",
policy => policy.RequireClaim("StockEdit", "true"));
options.AddPolicy("StockDelete",
policy => policy.RequireClaim("StockDelete", "true"));
//CartStatistics
//Cart
options.AddPolicy("CartShow",
policy => policy.RequireClaim("CartShow", "true"));
options.AddPolicy("CartAdd",
policy => policy.RequireClaim("CartAdd", "true"));
options.AddPolicy("CartEdit",
policy => policy.RequireClaim("CartEdit", "true"));
options.AddPolicy("CartDelete",
policy => policy.RequireClaim("CartDelete", "true"));
//Categries
options.AddPolicy("CategriesShow",
policy => policy.RequireClaim("CategriesShow", "true"));
options.AddPolicy("CategriesAdd",
policy => policy.RequireClaim("CategriesAdd", "true"));
options.AddPolicy("CategriesEdit",
policy => policy.RequireClaim("CategriesEdit", "true"));
options.AddPolicy("CategriesDelete",
policy => policy.RequireClaim("CategriesDelete", "true"));
//BarItems
options.AddPolicy("BarItemsShow",
policy => policy.RequireClaim("BarItemsShow", "true"));
options.AddPolicy("BarItemsAdd",
policy => policy.RequireClaim("BarItemsAdd", "true"));
options.AddPolicy("BarItemsEdit",
policy => policy.RequireClaim("BarItemsEdit", "true"));
options.AddPolicy("BarItemsDelete",
policy => policy.RequireClaim("BarItemsDelete", "true"));
});
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Products}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapRazorPages();
});
}
}
I Tried to Clear Cookies in Browser and it work So I search About Update in My Coding to Solve this Problem
Related
I need to add custom middleware between authentication and authorization that will add ClaimsIdentity to User that in context.
public class PermissionsMiddleware
{
private readonly RequestDelegate _next;
public PermissionsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IAccountService accountService)
{
if (context.User.Identity == null || !context.User.Identity.IsAuthenticated)
{
await _next(context);
return;
}
var userSub = context.User.FindFirst(ClaimConstants.Subject)?.Value;
if (string.IsNullOrEmpty(userSub))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("User 'sub' claim is required");
return;
}
var permissionsIdentity = await accountService.GetUserPermissionsIdentity(userSub);
if (permissionsIdentity == null)
{
context.Response.StatusCode = 401;
return;
}
context.User.AddIdentity(permissionsIdentity);
await _next(context);
}
}
But context.User.Identity.IsAuthenticated is always false.
My ConfigureServicesmethod
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddCoreServices();
services.AddControllers();
services.AddDbContext<AppDbContext>(
options => options.UseMySql(
connectionString,
ServerVersion.AutoDetect(connectionString),
b => b.MigrationsAssembly(migrationsAssembly))
.UseSnakeCaseNamingConvention());
services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IEmailSender, EmailSender>();
services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
services.AddScoped<IAccountManager, AccountManager>();
services.AddTransient<IDatabaseInitializer, AppDbInitializer>();
services.AddScoped<IGrantValidationService, DelegationGrantValidationService>();
services.Configure<AppSettings>(Configuration);
services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = false;
options.SignIn.RequireConfirmedEmail = false;
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
});
var applicationUrl = Configuration["ApplicationUrl"].TrimEnd('/');
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(
connectionString,
ServerVersion.AutoDetect(connectionString),
b => b.MigrationsAssembly(migrationsAssembly))
.UseSnakeCaseNamingConvention();
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(
connectionString,
ServerVersion.AutoDetect(connectionString),
b => b.MigrationsAssembly(migrationsAssembly))
.UseSnakeCaseNamingConvention();
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
})
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<ProfileService<ApplicationUser>>()
.AddDelegationGrant<ApplicationUser, string>();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = applicationUrl;
options.SupportedTokens = SupportedTokens.Jwt;
options.RequireHttpsMetadata = false;
options.ApiName = IdentityServerConfig.ApiName;
});
//services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
//services.AddSingleton<IAuthorizationHandler, CreateUserAuthorizationHandler>();
//services.AddSingleton<IAuthorizationHandler, EditUserAuthorizationHandler>();
//services.AddSingleton<IAuthorizationHandler, DeleteUserAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy(Policies.ViewUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewUsers));
options.AddPolicy(Policies.CreateUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.CreateUsers));
options.AddPolicy(Policies.EditUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.EditUsers));
options.AddPolicy(Policies.DeleteUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.DeleteUsers));
options.AddPolicy(Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewRoles));
options.AddPolicy(Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
options.AddPolicy(Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ManageRoles));
options.AddPolicy(Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
});
My Configure method
app.UseCors(x => x.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMiddleware<ErrorHandlerMiddleware>();
//app.UseSwagger();
//app.UseSwaggerUI();
app.UseRouting();
app.UseIdentityServer();
app.UseMiddleware<PermissionsMiddleware>();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
First off, make sure the Authority and ApiName are the same in the TOKEN as in your API. (I think this is case sensitive.) This is something you haven't provided so I cannot verify.
Also 1 line before this line:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
add the following line:
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
EDIT: Also remove this line in your startup:
app.UseIdentityServer();
This most likely overrides your own settings for identityserver.
I am creating 2 web applications using ASP.net core 3.1 .
I need to call 1st application in iFrame in second application it resets the login identity and when i click any other link in my website it redirects to login page. How to avoid this?
Below the jQuery code I use to load iFrame .
$(document).ready(function () {
$(function () {
$('#previewBot').on('click', function () {
var client = $("#client_id_Broker").html();
var secret = $("#session_secret").html();
var siteid = $("#site_id_Broker").html();
var site = window.location.hostname;
var chatpopContent = "<iframe src='";
var number = 1 + Math.floor(Math.random() * 6);
var URIChat = "https://localhost:44355/?client=" + client + "&siteid=" + siteid + "&secret=" + secret + "&site=" + site + "&r=" + number ;
chatpopContent += URIChat;
chatpopContent += "' id='iView' frameborder='1' class='frame-container' referrerpolicy='no-referrer' rel='noreferrer' async='false' ></iframe>";
$("#showpreview").empty();
$("#iView").remove();
$("#showpreview").append(chatpopContent);
});
});
});
Below is my startup config, is there anything wrong in this? or what should be added to avoid redirecting to login page after calling iframe?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConStringLocal")));
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstffgsfsdfsfsfff123456789-_";
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(o => {
o.ExpireTimeSpan = TimeSpan.FromDays(5);
o.SlidingExpiration = true;
});
services.AddMvc(o =>
{
//Add Authentication to all Controllers by default.
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
}).AddNToastNotifyNoty(new NotyOptions
{
Layout = "bottomRight",
ProgressBar = true,
Timeout = 5000,
Theme = "metroui"
});
services.Configure<DataProtectionTokenProviderOptions>(o =>
o.TokenLifespan = TimeSpan.FromHours(3));
services.AddAutoMapper(typeof(Startup));
services.AddRazorPages();
services.AddControllers();
services.AddSignalR();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
//services.AddSingleton<IRepository, Repository>();
services.AddScoped<ISitesRepository, SitesRepository>();
services.AddCors();
services.AddControllersWithViews()
.AddNewtonsoftJson()
.AddXmlDataContractSerializerFormatters();
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseNToastNotify();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapHub<ChatAdminHub>("/chatAdminHub");
});
}
I was able manage to solve the issue by adding below cookiePolicyOptions.
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.OnAppendCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "myappcookieName";
options.Cookie.SameSite = SameSiteMode.None;
});
I'm working with .NetCore API and MVC. Everything works on the local server. But the session does not occur after publishing the site.
The operation of the project is as follows:
User come with token ID to website.
I'm parsing it and then saving important variables to session.
I'm getting values from session.
...
As you can see If I get error on session other steps will fail.
I tried too many ways but none of them worked.
I'm adding Startup.cs/ConfigureServices and Configure methods.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddMvc().AddControllersAsServices();
services.AddWkhtmltopdf("wkhtmltopdf");
services.AddHttpContextAccessor();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(600);//You can set Time
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddAuthentication();
services.AddScoped<Business.Business, Business.Business>();
services.AddSingleton<SharedViewLocalizer>();
#region Localization and Language
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var cultures = new[] {
new CultureInfo("tr-TR"),
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = cultures;
options.SupportedUICultures = cultures;
});
#endregion
services.AddMvc(option =>
{
option.EnableEndpointRouting = false;
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.AddRazorPages();
services.AddServerSideBlazor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseDeveloperExceptionPage();
//app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
#region Language Options
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
var cookieProvider = options.Value.RequestCultureProviders
.OfType<CookieRequestCultureProvider>()
.First();
var urlProvider = options.Value.RequestCultureProviders
.OfType<QueryStringRequestCultureProvider>().First();
cookieProvider.Options.DefaultRequestCulture = new RequestCulture("tr-TR");
urlProvider.Options.DefaultRequestCulture = new RequestCulture("tr-TR");
cookieProvider.CookieName = CookieRequestCultureProvider.DefaultCookieName;
options.Value.RequestCultureProviders.Clear();
options.Value.RequestCultureProviders.Add(cookieProvider);
options.Value.RequestCultureProviders.Add(urlProvider);
app.UseRequestLocalization(options.Value);
#endregion
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
#region Routing
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"areas",
"{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Login}/{id?}");
endpoints.MapRazorPages();
//endpoints.MapBlazorHub();
//endpoints.MapFallbackToController("Index", "Home");
});
#endregion
}
options.Cookie.SameSite = SameSiteMode.None must be used to allow cross-site cookie use.
https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-5.0
The order of middleware is important. Call UseSession after UseRouting and before UseEndpoints. See Middleware Ordering.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
If your production environment consists of multiple servers, the easy way out (but not the recommended way), is to enable sticky sessions in your load balancer.
Using distributed cache is the recommended way when using multiple servers. More info: https://dzone.com/articles/aspnet-core-session-storage-strategies
You should consider not to use sessions at all, that will make things a lot easier for you.
I have a website set up and running, and when going through my logs I found the error posted below. I have found similar issues, but they were all using odic and not Identity.
I tested locally and the same issue appears.
I have https and www redirection set up, so tried to disable those and still got the same result.
I tried moving app.UseAuthentication(); around, which did no good either.
I have the add trailing slash option enabled, disabling that had no effect...
I'm stumped.
Exception
System.Exception: An error was encountered while handling the remote login. ---> System.Exception: Correlation failed. --- End of inner exception stack trace --- at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
As seen with the odic issues I read up on, refreshing the page will allow the process to continue.
my ConfigureServices looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("SqlConnectionString")));
services.AddDbContext<LoggingDbContext>(options => {
options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString"));
});
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddDefaultUI()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication()
.AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
})
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection =
Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
})
.AddFacebook(facebookOptions => {
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
services.Configure<DataProtectionTokenProviderOptions>(options =>
{
options.TokenLifespan = TimeSpan.FromDays(7);
});
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(1);
});
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
options.HttpsPort = 443;
});
services.AddSession();
//services.AddResponseCaching();
var adminPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole(Administrator)
.Build();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdmin", policy => {
policy.RequireAuthenticatedUser();
policy.RequireRole(Administrator);
});
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Users");
options.Conventions.AuthorizePage("/ViewProfile");
options.Conventions.AuthorizePage("/NewsFeed");
options.Conventions.AuthorizePage("/PostEdit");
options.Conventions.AuthorizePage("/PostDelete");
options.Conventions.AuthorizePage("/Message");
options.Conventions.AuthorizePage("/RelationshipManager");
options.Conventions.AuthorizeAreaFolder("Administration", "/", "RequireAdmin");
options.Conventions.AllowAnonymousToPage("/Index");
options.Conventions.AllowAnonymousToPage("/Privacy");
options.Conventions.AllowAnonymousToPage("/Terms");
options.Conventions.AllowAnonymousToAreaPage("Horses", "/HorseBrowser/Index");
options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/AddHorse");
options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/EditHorse");
options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/DeleteHorse");
options.Conventions.AuthorizeAreaPage("Horses", "/MakeAnOffer");
options.Conventions.AuthorizeAreaPage("Horses", "/Oops");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(x => {
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
x.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
}).AddFacebookWebHooks();
services.Configure<RouteOptions>(options =>
{
options.AppendTrailingSlash = true;
});
services.AddSignalR().AddMessagePackProtocol();
services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
services.Configure<MailGunSettings>(Configuration.GetSection("MailGunSettings"));
services.Configure<FacebookOptions>(Configuration.GetSection(nameof(FacebookOptions)));
services.AddSingleton<IUploadSettings>(Configuration.GetSection("UploadSettings").Get<UploadSettings>());
services.AddSingleton<IVapidKeys>(Configuration.GetSection("VapidKeys").Get<VapidKeys>());
services.AddTransient<IEmailService, EmailService>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddHttpClient<CountriesService>();
services.AddAngleSharp();
services.AddSingleton<GenericPageScraper>();
services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();
services.AddScoped<IChatRepository, ChatRepository>();
services.AddScoped<IPostRepository, PostRepository>();
services.AddScoped<IHorseRepository, HorseRepository>();
services.AddScoped<IDeviceRepository, DeviceRepository>();
services.AddScoped<IWebPushRepository, WebPushRepository>();
services.AddScoped<ILogsRepository, LogsRepository>();
}
And my Congure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//app.UseSerilogRequestLogging();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseAspNetCoreExceptionHandler();
// 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();
var options = new RewriteOptions()
.AddRedirectToHttpsPermanent()
.AddRedirectToWwwPermanent();
app.UseRewriter(options);
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSignalR(hubs =>
{
hubs.MapHub<NagbookHub>("/hub");
hubs.MapHub<PostHub>("/posthub");
});
app.UseSession();
//app.UseResponseCaching();
app.UseMvc();
}
The error is with any provider be it Microsoft, Facebook or Google.
I am using inprocess and hosting is on IIS within a VPS running server 2012R2.
Any help with this is appreciated.
Thanks in advance :)
Ok, so face palm time...
All I had to do is change the cookie policy to:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
});
Pretty obvious really, and always right there at the top of the code... urgh.
Try checking you callback url and return url.I fixed this error by changing return url.
I encounter this error in my API IDX10214: Audience validation failed. Audiences: 'https://localhost:44337/resources'. Did not match: validationParameters.ValidAudience: 'joborderingapi' or validationParameters.ValidAudiences: 'null'
I've been trying to solve this for 2 days already and can't figure out yet about how to solve it.
I have the following applications:
Client App (Angular 7)
Identity Server
API
I was able to login successfully to Identity Server in my Client app and was able to get the token but when I used the token to connect to the API method it throws this error IDX10214: Audience validation failed. Audiences: 'https://localhost:44337/resources'. Did not match: validationParameters.ValidAudience: 'joborderingapi' or validationParameters.ValidAudiences: 'null'.
I followed the answer from Identity Server 4 with EF Identity DB Issue and checked the three tables (ApiResources, ApiScopes, ClientScopes), the values are correct, joborderingapiis enabled in ApiResources, in ApiScopes it is linked to ApiResource and in ClientScopes it is linked to the Client
Here is my API Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var apiIdpAuthority = Configuration["AppSettings:IdpAuthority"];
var apiName = Configuration["AppSettings:ApiName"];
var apiSecret = Configuration["AppSettings:ApiSecret"];
var requireHttps = Convert.ToBoolean(Configuration["AppSettings:RequireHttps"]);
var httpsPort = Configuration["AppSettings:HttpsPort"];
var applicationUrl = Configuration["AppSettings:ApplicationUrl"];
services.Configure<ClientAppSettings>(Configuration.GetSection("ClientAppSettings"));
services.AddDbContext<JobOrderingDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("JobOrderingDB")));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
IdentityModelEventSource.ShowPII = true;
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = apiIdpAuthority;
options.RequireHttpsMetadata = requireHttps;
options.ApiName = apiName;
options.ApiSecret = apiSecret;
});
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins(apiIdpAuthority, applicationUrl)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials();
});
});
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
});
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = Convert.ToInt32(httpsPort);
});
}
// 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();
}
else
{
app.UseHsts();
}
app.UseCors("default");
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseHttpsRedirection();
app.UseCookiePolicy();
var locale = Configuration["SiteLocale"];
var supportedCultures = new List<CultureInfo> { new CultureInfo("en-US") };
if (supportedCultures.Where(x => x.Name == locale).Count() == 0)
{
supportedCultures.Add(new CultureInfo(locale));
}
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
DefaultRequestCulture = new RequestCulture(locale)
};
app.UseRequestLocalization(localizationOptions);
app.UseAuthentication();
app.UseMvc();
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
Identity Server Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//var microsoftClientId = Configuration["MicrosoftClientId"];
// var microsoftClientSecret = Configuration["MircosoftClientSecret"];
var azureADClientId = Configuration["AzureADClientId"];
var azureADClientSecret = Configuration["AzureADClientSecret"];
var azureADEndPoint = Configuration["AzureADEndPoint"];
var issuerUri = Configuration["IssuerUri"];
string connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<IdentityServerDataContext>(options => options.UseSqlServer(connectionString));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthentication()
// .AddCookie()
.AddOpenIdConnect("AAD", "Azure AD", options =>
{
options.Authority = string.Format("https://login.microsoftonline.com/{0}", azureADEndPoint);
options.ClientId = azureADClientId;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
});
IdentityModelEventSource.ShowPII = true;
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddIdentityServer() .AddSigninCredentialFromConfig(Configuration.GetSection("SigninKeyCredentials"), _logger)
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
})
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// this will do the initial DB population
// InitializeDatabase(app);
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentityServer();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Note: I only encounter this issue when I use the local login. It is working fine if I use the Azure AD login, I was able to connect to the API using the authorization token from the client app