Back button issue in MVC 6 after login and logout - asp.net-core

I am trying to restrict user to click back button after Login/Logout into the application.
If the user is logged in into the application, then after clicking on back button Login view should not be displayed and if user is logged out from the application then clicking on back button LogOff view should not be displayed.
I have already used caching technique which is given in number of links, but seems its not working.
This CacheAfterLogout link and done exactly as it is, still problem is not solved. I am using asp.net identity framework.
Could someone help on this ?

To disable caching you can apply the following to each controller you wish to disable caching on
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
You can also setup named cache profiles and configure the settings at runtime.

Cache can be disabled by applying the [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] on each controller for which you wish to disable caching.
This can be applied to all controllers globally by adding your custom filter in startup.cs while configuring MVC services with ASP.Net Core 1.0.-* and MVC6.
First create a custom cache filter implementing the ResponseCacheAttribute as follows
public class ResponseCacheFilter : ResponseCacheAttribute
{
public ResponseCacheFilter() : base()
{
Location = ResponseCacheLocation.None;
NoStore = true;
}
}
This should be added in startup.cs file as follows.
public void ConfigureServices(IServiceCollection services)
{
// Add framework and custom services.
services.AddMvc(config =>
{
config.Filters.Add(new ResponseCacheFilter());
});
}
See the configuration of ResponseCache at https://docs.asp.net/en/latest/performance/caching/response.html#responsecache-attribute

Just Add This Code in Global.asax.cs
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}

Just add these lines to your Global.asax.cs file.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}

Related

Startup.vb DonĀ“t recognize StarttupAuth.vb Class [duplicate]

I'm getting an error when I'm attempting to run my page says that,
The name 'ConfigureAuth' does not exist in the current context
in my Stratup Class. I'm sure all AspNet Identity libraries are installed. What do I need to do next, to try to fix this?
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(project_name.Startup))]
namespace project_name
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
If you are using default Visual Studio project template, the ConfigureAuth method could be found in partial class Startup.Auth.cs. So make sure you didn't break anything when modifying project structure.
This is an example of ConfigureAuth method:
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
I had similar issue, To fix the issue I removed .App_Start from namespace in Startup.Auth.cs file. After that I was able to see the reference.
It is either:
[assembly: **OwinStartup**(typeof(Project-Name.Startup))]
namespace project-name
{
public partial class Startup
{
public void **Configuration**(IAppBuilder app)
{
OR
[assembly: **OwinStartupAttribute**(typeof(Project-Name.Startup))]
namespace project-name
{
public partial class Startup
{
public void **ConfigureAuth**(IAppBuilder app)
{
Either rename OwinStartupAttribute to OwinStartup
OR Configuration to ConfigureAuth
Kindly I note that the two partial classes (Startup.Auth.cs and Startup.cs) should be in the same namespace which is the root of the project, just change the namespace of Startup.Auth.cs to the same namespace of the Startup.cs
Make sure when you originally create the project that there are no spaces in the name.
e.g. my app was called "DevOps Test" which was giving me errors when I ran it.
I recreated it as "DevopsTest" and no longer had these issues
namespace PAYOnline.App_Start
delete App_Start only namespace PAYOnline => It's welldone

Asp.net core, when in debug, bypass Authorization

I have a test web site which uses the aspnetCore [AuthorizeAttribute] at the entire controller level to ensure only Authenticated Users can hit this site.
While we debug and test new features, we constantly have to comment out the attribute in each controller, which I know will be easy to forget and might get merged some day.
We've had good success with checking to see if a Debugger is attached before...I am wondering which AuthenticationScheme I should specify to allow anonymous, only if debugging.
I extend the base AuthorizeAttribute so I have an easy place to shim in some code.
public class MyAppAuthorizeAttribute : AuthorizeAttribute
{
public MyAppAuthorizeAttribute()
: base(Policies.MyAppAuthorize)
{
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Skipping auth for debug"); //we hit this line but...
this.AuthenticationSchemes = AllowAnonymousAttribute //this setting does not work
}
else
{
this.AuthenticationSchemes = "IntegratedWindowsAuthentication";
}
}
}
Seems like a good candidate for IWebHostingEnvironment.IsDevelopment():
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (!env.IsDevelopment())
{
app.UseAuthentication();
app.UseAuthorization(); // maybe optional, depends on your case
}
...
Your requirement may be necessary in some cases where the user is required to be authenticated BUT not actually referenced in the code (e.g: the code does not access any info on the current identity, especially related to the business model of the user).
So I assume that you are aware of that because the following will just simply remove the requirement to check for authenticated user when the code runs in the development environment. There is another way to auto sign-in a dummy user which can be better in some scenarios.
Here is the first solution, it configures a default policy only which does not include the DenyAnonymousAuthorizationRequirement (which is the only requirement contained in the default policy). That means if you have multiple policies used somewhere (with AuthorizeAttribute), only the default will be ignored (while debugging). The second solution (shown later) may suit that scenario better.
//inject IHostingEnvironment in the Startup constructor
public Startup(IConfiguration configuration, IHostingEnvironment env){
HostingEnvironment = env;
}
public IHostingEnvironment HostingEnvironment { get; }
//in the ConfigureServices method in Startup.cs
services.AddAuthorization(o => {
if (HostingEnvironment.IsDevelopment()){
o.DefaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
//there should be at least 1 requirement
//here we add a simple always-passed assertion
.RequireAssertion(e => true).Build();
}
//...
});
We need to use IHostingEnvironment (in .net core 2.2, since 3.0 we have 2 alternatives IWebHostEnvironment and IHostEnvironment) so we inject it in the Startup constructor and store it in a readonly property (as you see above). There is another way is try to get the ASPNETCORE_ENVIRONMENT variable directly like this:
var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";
Here is the second solution in which you use a custom global IAsyncAuthorizationFilter to auto sign-in a dummy user (so it's always authenticated for all requests).
public class AllowAnonymousFilterAttribute : Attribute, IAsyncAuthorizationFilter
{
readonly IHostingEnvironment _hostingEnvironment;
public AllowAnonymousFilterAttribute(IHostingEnvironment env){
_hostingEnvironment = env;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (_hostingEnvironment.IsDevelopment() && !context.HttpContext.User.Identity.IsAuthenticated)
{
//prepare a dummy user to auto sign-in
HttpContext.User = new ClaimsPrincipal(new[] {
new ClaimsIdentity(new []{ new Claim(ClaimTypes.NameIdentifier,"admin")},
CookieAuthenticationDefaults.AuthenticationScheme)
});
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
HttpContext.User);
}
}
}
Register the filter globally, here I write code for .net core 2.2:
services.AddMvc(o => {
//register the filter only for development (should be debugging)
if (HostingEnvironment.IsDevelopment()){
o.Filters.Add<AllowAnonymousFilterAttribute>();
}
//...
});
I'm sure there are still some other solutions but what I've introduced here are fairly simple and good enough for your purpose.
P/S: the first solution I've introduced above suits for .net core 2.2 (actually currently I do not have access to newer versions of .net core, it's a pity). For the newer versions, the Authorization middleware is separate so you may just simply not call .UseAuthorization() middleware in the Configure method (of course for development environment only) as one other answer suggests.

Restrict account registration to only Admin users with asp.net identity authentication

I am creating a Blazor server app that requires authenticated users in order to prevent external access, and I would like to limit the ability to register new accounts to be only available to Administrator users to prevent unwanted accounts from being created.
I'm using Identity user accounts, scaffolded out for Blazor. Solutions like this at least disable the registration, but from there I need to be able to enable it again for administrative users. I attempted to recreate the register page as a Blazor component, however, using the generated RegisterModel did not seem to work for me.
Upon a large amount of searching - the answer ended up being relatively simple. Muhammad Hammad Maroof's solution although technically correct, confused me and was mostly unhelpful for working with the register page specifically.
As I am using Role-Based Authentication scaffolded out from Blazor - in a seperate razor page I use this code to set up roles:
#code {
protected override async Task OnParametersSetAsync()
{
await SetUpAuth();
}
private async Task SetUpAuth()
{
const string Manager = "Manager";
string[] roles = { Manager };
foreach (var role in roles)
{
var roleExist = await roleManager.RoleExistsAsync(role);
if (!roleExist)
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
var user = await userManager.FindByEmailAsync(config.GetValue<string>("AdminUser"));
if (user != null)
{
await userManager.AddToRoleAsync(user, Manager);
}
}
}
Allowing the appropriate user to be marked as an administrator. This page has the [AllowAnonymous] tag on it in order to allow the administrative user as dictated by "AdminUser": "SomeEmail#test.com", in the appsettings.json page to be able to access the site on initial setup.
Preventing access to the Blazor site itself from anonymous users was as simple as adding this line to ConfigureServices in the startup class (Code taken from Microsoft Docs)
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
From this, allowing access to the register page was significantly easier than I had initially thought (likely due to my lack of .net experience). To do so, all you have to do is locate the Register.cshtml.cs page (I couldn't initially find the controller method Muhammad had mentioned) which I did by using visual studio to right click on the Register Model and then go to definition. This should take you to the Register.cshtml.cs page with the RegisterModel class. In order to restrict access to this page for only a specific role of users, all you have to do is change the [AllowAnonymous] tag above the class to look similar to this:
[Authorize(Roles ="Manager")]
public class RegisterModel : PageModel
It's important to note that the same technique used to secure the register page could be used to secure any of the of the other scaffolded Identity pages. For applications where you may have more than a few roles, the method provided by Muhammad of using policy based authorization may be the way to go, and this link he provided is a great tutorial for setting up and using that form of authentication.
//FORCE autentication for all RAZOR PAGES except [AllowAnonymous]
services.AddControllers(config => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
Only adding this code to my startup.cs solved my problem.
Here's how I am doing it in asp.net core mvc app
C# Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy(ADMIN_ACCESS, policy => policy.RequireRole($"{UserType.Admin}"));
});
}
[Authorize("AdminAccess")]
public class AdminController : Controller
{
//Some action methods here
}

How to add global metadata to ASP.NET Core logging?

I'd like to add my app's build number to all logs in an ASP.NET Core 3.1 app that is using Application Insights for log storage. Is this possible without having to use BeginScope and EndScope everywhere? I assumed it would be part of the ConfigureLogging startup hook, but didn't see anything. I've done this in the past with Serilog's enrichers, but am not using that library currently.
You can achieve that with TelemetryInitializer. (https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-filtering-sampling#addmodify-properties-itelemetryinitializer)
public class BuildNumberTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
(telemetry as ISupportProperties).Properties.Add("BuildNumber", "ValueForBuildNumber");
}
You need to add this initializer to the config, which is done like below if you are on Asp.Net Core applications.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, BuildNumberTelemetryInitializer >();
}

Override razor views in asp.net core razor pages

In asp.net core mvc, I had multiple locations specified for the views. so, if view was missing in one location, it gets fetched from the other location.
I have a CMS with asp.net core mvc where controllers and views comes in a compiled library. If I don't want to use the view from the library, it's easy to add a new one e.g. /Views/ControllerName/Index.cshtml and then the application will use this view instead of fetching from the library.
How can it be done in razor pages? Basically, I want to have an option to override the razor view of any page by adding a .cshtml file in a location.
Use an IViewLocationExpander, adding your custom location(s) before the default ones.
Here's an example that would look into an "Override" folder:
public class MyViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(
ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
// {2} = Area
// {1} = Controller
// {0} = Action
var locations = new string[] { "/Views/Override/{2}/{1}/{0}.cshtml" };
return locations.Union(viewLocations);
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
Then register it in your Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new MyViewLocationExpander());
});
}
I didn't get this to work in ASP.NET Core 2.2 using the other solutions suggested here (IViewLocationExpander or PageViewLocationFormats). What worked for me was using a PageRouteModelConvention in combination with an ActionConstraint.
Here's a similar solution where this has been used for localization:
PageRouteModelConvention and ActionConstraint
Configuration in Startup