I've project in ASP NET Core 3.1 with Windows Authentication. I would like to use custom error code page.
This a basic example.
In HomeController :
[Route("/Error/401")]
public IActionResult StatusCode401()
{
HttpContext.Response.StatusCode = 401;
return View("ErrorUnauthorized");
}
But when I call StatusCode401 method, Windows prompt dialog (login, password) appears, if I cancel it, I see my custom view.
If I disable Windows Authentication, it's works fine.
How disable Windows prompt dialog when I use Windows Authentication ?
Thanks
You can open the web.config,
And then find the statusCode 401, change the responseModel from ExecuteURL to File
<system.webServer>
<httpErrors errorMode="Custom" >
<error statusCode="403" subStatusCode="0" prefixLanguageFilePath="" path="***" responseMode="ExecuteURL" />
<error statusCode="401" subStatusCode="2" prefixLanguageFilePath="" path="***" responseMode="File" />
....
</httpErrors>
</system.webServer>
Related
Framework asp.net core 2.2 -
After developing and managed to get the Windows logged in user in the local host (IIS express):
[Route("getUser")]
[HttpGet]
public IActionResult GetUser()
{
var NullUser = User.Identity.Name; //return null
var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
return Ok(currentUser.Name);
}
and LaunchSettings.json:
"iisSettings":{
"windowsAuthentication": false,
"anonymousAuthentication": true
...
}
So far, so good !
Now - I'm publishing the application to an IIS, with the web.config:
<system.web>
<authentication mode="Windows"></authentication>
<identity impersonate="false" /> //This is because I'm getting the username by code
</system.web>
<system.webServer>
<aspnetCore processPath=....... forwardWindowsAuthToken="true" hsotingModel="InProcess">
</aspnetCore>
<security>
<authentication>
<anonymousAuthentication enabled ="false" />
<windowsAuthentication enabled ="true" />
</authentication>
</security>
</system.webServer>
These are the basic properties of the application pool which the application works with:
.NET CLR version: No Managed Code
Managed pileline mode: Integradted
Advanced:
Process Model:
Identity: ApplicationPoolIdentity
And then, when running the application, I'm getting error 500.19 pointing on the authentication section (ignore typo errors - it is free text writing - not copy + paste):
AnonymousAuthenticationModule
Config error
This configuration section cannot be used at this path. This happens when the section is
locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set
explicitly by a location tag with overrideMode="Deny"; ot the legacy allowOverride="false"/
Config Source:
<authentication>
<anonymousAuthentication enabled ="true" />
<windowsAuthentication enabled ="true" />
web.config.png
I am pretty sure "anonymousAuthentication enabled" should be set to false.
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/authentication/windowsauthentication/
As #Lex Li mentioned - the problem was configuration line items which are irrelevant to ASP.NET core, but to ASP.NET 4.5 - I removed them as he advised
I’m trying to remove the response Server header from an Azure Web App ( with an ASP Net core application )
After many tries of changing the web.config and removing the header in app code using a middleware, Microsoft doesn’t give up and set the response header to Server: Microsoft-IIS/10.0 :)
The problem appears only when I’m trying to access the server on http (not https). Response code from the server is 301, and this is the only response that has the Server header.
Checking the logs I was not able to find any request to http://, and perhaps this is why I’m not able to remove header, because the request is not process in my application code.
A solution that I’m thinking is to disable the azure HTTPS only and do the redirect to https in my code (I tested and is working - server header is removed)
Is there another workaround without disabling the HTTPS only option?
Here is what I tried
Startup.cs
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("server", string.Empty)
}
app.UseHttpsRedirection();
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime enableVersionHeader="false" />
<!-- Removes ASP.NET version header. -->
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true" />
<!-- Removes Server header in IIS10 or later and also in Azure Web Apps -->
</security>
<rewrite>
<outboundRules>
<rule name="Change Server Header"> <!-- if you're not removing it completely -->
<match serverVariable="RESPONSE_Server" pattern=".+" />
<action type="Rewrite" value="Unknown" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
UPDATE
When the URL of http:// is requested, IIS will process it, this time without code. So we can't control it by the code, we can only set it on the server, such as some scripts or tools. But on Azure, we have no way to directly operate as a physical server, so after exploration, I suggest that Front Door can be used to deal with this problem. Hiding server information through proxy should be a better way.
After my test, the server information is hidden, you can refer to this document . We can see from the picture that there is no 301 redirect request, and no server information in other requests.
PREVIOUS
You need to modify Global.asax.cs and Web.config file in your program.
In Global.asax.cs.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
PreSendRequestHeaders += Application_PreSendRequestHeaders;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
}
And In Web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
Then u can deploy your app. After the above code modification, access to the interface or static resources can see that the server information is modified, of course, it can also be deleted by Remove.
You also can handle special event by http status code.
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
int StatusCode= HttpContext.Current.Response.StatusCode;
// handle like http status code 301
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
I've inherited MVC4 application. It looks like Windows Authentication is used, but I also was told that "Active Directory Authentication" is used for some permissions. I do not see anything in web.config about Active Directory.
In web.config:
<authentication mode="Windows" />
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21bf1234ad634e53" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
In Controller:
[Authorize(Roles = #"ABCD\EFG"), HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "UnauthorizedUser", Order = 1)]
public class HomeController : Controller
{ .............
}
public ActionResult MyAction()
{
if (!User.IsInRole(#"ABCD\EFG"))
{
// some code
}
//.............
}
Is "Active Directory Authentication" used in this application ?
Thank you
The windows authentication will indeed integrate with Active Directory as long as the application server is on the domain your users are registered in.
The below line in your config file enables such functionality.
<authentication mode="Windows" />
This post might help you get further:
Configure ASP.NET MVC for authentication against AD
I'm trying to debug in VS express 2013 with my MVC4 application.
In a view, I've added a nonsense link, such as link, but I don't see the intended View when I click on the link, I see the IIS page.
I did this by creating an ErrorController which is
public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
}
}
My view remains as the default, I didn't update it.
And my webconfig is
<customErrors mode="On" defaultRedirect="~/Error">
</customErrors>
The routes are the default!
The IIS message is
HTTP Error 404.0 - Not Found
If I type in http://localhost:53258/error/ then I see the page, suggesting that the mapping is fine.
What have I done wrong?
Check for this in your web.config, and add it if you don't have it:
<httpErrors errorMode="Custom" existingResponse="PassThrough" />
Try updating your customErrors node to add this:
<error statusCode="404" redirect="~/Error" />
Thus, your custom errors section would look like:
<customErrors mode="On">
<error statusCode="404" redirect="~/Error" />
</customErrors>
i developed a website(MVC 5) and upload it on a iis7 on a web server.
i handle errors on method
protected void Application_Error(){}
on the Global.asax.
yesterday i did some tests on it and i saw when i enter this url
http://www.xxxx.com/.
i can get invalid rout on Application_Error method but when i entered that URL with 3dotes or more like this URL
http://www.xxxx.com/...
i saw a webpage with this content and Application_Error not works because i have no default page or view with this content on my project.
The page cannot be displayed because an internal server error has occurred.
i did some test on another website on the internet and i saw some of theme has the same issue and i think i should do some config on my IIS.
if yes , what config(s) i should set on my IIS and if no what i can do with my project until i can handle it?
You can try this configuration in the web.config file:
<customErrors mode="On|Off|RemoteOnly" defaultRedirect="URL">
<error statusCode="404" redirect="URL" />
<error statusCode="402" redirect="URL" />
<error statusCode="500" redirect="URL" />
</customErrors>
Example:
I created a ErrorHandlerController with the following ActionResult's:
//This action return a view that show the http error you specified.
public ActionResult Error()
{
return View();
}
//This action return a view that show the 404 http error captured.
public ActionResult NotFoud()
{
return View();
}
//This action return a view that show the 402 http error captured.
public ActionResult Unauthorized()
{
return View();
}
In the web.config file of my project:
<customErrors mode="RemoteOnly" defaultRedirect="~/ErrorHandler/Error">
<error statusCode="404" redirect="~/ErrorHandler/NotFoud" />
<error statusCode="402" redirect="~/ErrorHandler/Unauthorized" />
<error statusCode="500" redirect="~/ErrorHandler/Error" />
</customErrors>
NOTE: Change the URL with your CustomURL desired.
Help: https://msdn.microsoft.com/en-us/library/h0hfz6fc%28v=vs.85%29.aspx