How can I configure IIS to prompt for passwords on a web application running on ASP.NET MVC in IIS?
I want to password protect the Views\ApplicationLog\ folder, so that browsers ask for username and password when users try to access this folder.
How could I accomplish this? Can this be done directly from IIS, or do I need to set something in web.config?
Please try to be thorough, I don't know IIS all that well.
If you're using MVC, you shouldn't have anyone directly accessing anything under your Views folder at all. Instead, your Controllers (or their actions) will assert whatever authentication is required.
In this specific case, it looks like your controller is named ApplicationLogController. So you'd add an [Authorize] attribute on the controller as follows, and it will automatically ensure that anyone accessing the controller methods is authorized.
[Authorize] // You can also do [Authorize(Roles="MyRole,YourRole")], etc...
public class ApplicationLogController : Controller
{
...
}
In the IIS 6 manager, go to the "Directory Security" tab, click on "Edit" then check "Integrated Windows Authentication" and / or "Basic Authentication" depending on the modes you want to support.
In system.web within your app's web.config:
<authentication mode="Windows">
<authorization>
<deny users="?" />
</authorization>
Related
I am creating a website in ASP.Net Core MVC and using IIS's automatic authentication to have users of the company automatically be validated through active directory. This is working as it should at the moment, however, I'd like to redirect users to a log in page if they can not be validated through IIS. I've seen other posts describing how to do this when using a normal authentication cookie, but not with this automatic authentication.
This is my current Configure Services method:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<IISServerOptions>(options =>
{
options.AutomaticAuthentication = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
So at the moment it is successfully locking out users who do not have AD authorization on a page marked [Authorize], I'd just like to redirect that locked out traffic to another page marked [AllowAnonymous]. Is there a way to modify the services.Configure method? So far I do not see anything.
What you're using is called Windows Authentication. The reference to AutomaticAuthentication just tells IIS to automatically set HttpContext.User with the user details (otherwise it doesn't, even if the authentication succeeded).
What you're looking for is really two authentication methods: For people with AD accounts (who are logged in with those accounts), log them in automatically using Windows Authentication. Otherwise, show a login screen and you can handle the authentication yourself.
I've done this before in ASP.NET MVC, but I haven't (yet) done it in ASP.NET Core. I'll describe what I did, but this isn't a complete solution since there's a missing piece for ASP.NET Core.
Use cookies for your main authentication method. Set it up like normal, with a login page where you validate the credentials and set the cookie.
Setup one controller action (lets say, /Login/SSO) that uses Windows Authentication. I did that using a location tag in the web.config. That is still likely the same in ASP.NET Core, I'm just not entirely sure how you pick up on that in the code. But the part in web.config would look something like this:
<location path="Login/SSO">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true"/>
<anonymousAuthentication enabled="false"/>
</authentication>
</security>
</system.webServer>
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
In the code for that action, assuming you can figure out how to grab the username from the Windows Authentication, you set the cookie and return a 200 OK (you don't need to return a view). If Windows Authentication fails, IIS will return a 401 on its own. (I think the <allow users="?"/> was just to prevent the cookie authentication from trying to redirect - but I can't remember)
The fancy trick is on the login page. Hide everything on the page by default. On page load, do an AJAX request to /Login/SSO. If it succeeds, then the user is logged in and you can forward them (via javascript) to the page they want. If it fails, just show the contents of the login page. That would look something like this (assuming you're using jQuery):
$(function() {
$.get("#Url.Action("SSO", "Login")").done(function(data) {
//success! forward to the page they want
window.location.replace(returnUrl);
}).fail(function() {
//failed - show login prompt
$("#loginBox").show();
});
});
With this setup, a user who can be authenticated using Windows authentication will hit the site, get redirected to the login page, the login page does a successful AJAX request that creates their cookie, and they get redirected back to the original page they wanted. Pretty seamless.
I have done a Admin Web site Using ASP.net, C# with MySQL data Base
My website is Only designed for admin So that I have less users like 4-5..
But I made a Mistake that My Web Site Has 9 Pages in that
If I Copy and Paste the URL of a Page Its opening without login credential's and sessions..
So Please Suggest me for this kind. So that it should check authentication when ever a page is opened.
I am new to asp.net and I tried for this kind But I found Only for SQL server
I want it For ASP.net, C# with MySQL Data Base
I don't want to use SQL-server as its commercial and expansive..
Use master page... check credential in master page...
or else
you should pass credential to one page from another page(query string or cookie etc)
check credential in load method in all pages
http://dotnet.tekyt.info/?p=31
http://www.dotnetfunda.com/codes/show/4580/login-page-using-mysql-database
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
http://www.codeproject.com/Articles/438259/Insert-Update-Search-and-Delete-CRUD-operation-usi
http://www.mono-project.com/MySQL
http://www.mono-project.com/Database_Access
http://www.codeproject.com/Articles/438259/Insert-Update-Search-and-Delete-CRUD-operation-usi
You can use web.config to deny access
<system.web>
<authorization>
<allow roles="admin" />
<deny users="*" />
</authorization>
</system.web>
I am using Form Authentication in my MVC3 web app. I have added following in root web.config:
<authentication mode="Forms">
<forms name=".FormsAuth" loginUrl="~/Home/Index" timeout="2880" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
When I launch my app, it redirects to http://localhost:22888/Home/Index?ReturnUrl=%2f instead http://localhost:22888. If I remove line <deny users="?"> then it redirects correctly but then Context.User.Identity.Name gives no value after login.
Please help.
Take a look at Securing your ASP.NET MVC 4 App and the new AllowAnonymous Attribute.
You cannot use routing or web.config files to secure your MVC application (Any Version). The only supported way to secure your MVC application is to apply the Authorize attribute ...
Quote
MVC uses routes and does not map URLs to physical file locations like WebForms, PHP and traditional web servers. Therefore using web.config will definitely open a security hole in your site.
The product team will have a communication if this changes in the future, but for now it is without exception the rule.
Examples:
Start with the default ASP.Net MVC project (internet/intranet).
Edit the web.config adding:
<location path="Home">
<system.web>
<authoirzation>
<deny users="*">
</authoirzation>
</system.web>
</location>
Run the project, by default you will use the Default route /Home/Index and you see content, simply bypassing the web.config with no changes to the default template. Why? Because the ASP.Net pipeline is comparing the URL requested to the location specified in the web.config. However, after the Authorization Event has been executed in the pipeline the routing taking place (Default routing or custom routing) and allows access to the supposedly restricted area.
Additionally, any MVC Redirect() will also by-pass the same security measures as again the routing takes place after the Authorization Pipeline Event.
When I launch my app, it redirects to http://:22888/Home/Index?ReturnUrl=%2f instead http://:22888.
If you are using the default template, authorization stores the returnUrl and redirects back to /Home/Index with the value %2f which is /. You can update the RedirectToAction code in the AccountsController to not append the returnUrl if it is /.
This is correct behavior of the runtime.
You told the engine to deny the access to unauthenticated users and also that the login url is located at ~/Home/Index.
This is why when you navigate to the default url / the engine makes the browser go to the login page and passes the return url, encoded / in this case.
The question is then: what you want to do if the correct behavior bothers you.
I resolved this issue by performing two modifications:
I removed deny users='?' line from web.config file. But then I was getting null in Context.User.Identity.Name
In HttpPost Login method, I was redirecting user after successful authentication using return View("Home"). When I changed it to return RedirectToAction("Home") I got value in Context.User.Identity.Name
Although a little late to the show, if you're still having issues, remember to look down at the sections in your web.config for other authorization rules (correctly or incorrectly set). There are some situations where mis-configurations to a resource at the root or subdirectory could cause endless redirects.
I'm learning ASP.NET MVC3 and I'm now examining the user handling.
My first problem would be (I know there is a lot about this subject in other threads, I just fail to find a good one with MVC3) that I want the login page to redirect me where I came from, or where I was redirected from.
In php perhaps I would add this url to the querystring, maybe.
But I need a way to do this somehow automatically, and this is a so common design pattern I was wondering if there is a "built in" way to do this.
What would be the cleanest, or preferred way to do this?
Also when I'm redirecting to a login page which would be the best way for checking and storing the url which I'm redirected from? I would check for the referrer in the request object and spit it out in the url as "?redirect=protected.html" but I'm not even sure how to properly do this.
Any advice on this subject would be appreciated.
MVC works the same way as ASP.NET.
If you use Forms Authentication a lot of those questions will be answered for you.
In your Web Config find the line that says authentication="Windows" and then change that to Forms
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" />
</authentication>
MVC 3 will actually give you the Account/LogOn route as part of the MVC 3 template project (check your models and see if you have one called AccountModel).
Then you just add Authorization to deny all users to your site:
<authorization>
<deny users="?"/>
</authorization>
by default this will send any person coming to your site off to your login.
So after you have validated that there login credentials are correct you set the AuthCookie the same as ASP.NET:
FormsAuthentication.SetAuthCookie(userName, false);
Form this you can the redirect to where ever you want.
to redirect back to where you came from use:
FormsAuthentication.RedirectFromLoginPage(userName, false);
Not forgetting the other useful statement of:
FormsAuthentication.SignOut();
Without Authentication the site wont let you access anywhere until you are logged in, so the CSS will stop working.
The locations I have added to make sure this doesnt happen are as follows:
<location path="Content">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
<location path="Scripts">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
In asp.net it is a ?returnUrl=...
(1) Make sure you have something like
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
in your root web.config.
(2) In your Controller you want to protect, add [Authorize] attribute above it.
Please create new project and select the Internet Application template rather than Empty one and you will get sample of the simple login process as well as changing password.
Note: Please read this as well: http://www.asp.net/mvc/tutorials/preventing-open-redirection-attacks
The sample shows after logging in process, it make sure the returnUrl is a local url by the Url.IsLocalUrl() helper to protect from Open Redirection Attack.
Update:
The best way is to implement your own custom login process after you really know the standard process for example instead of using the URL to track where the user come from, you can set a new cookie to store the returnUrl with httponly cookie and delete it just before redirect to previous page.
Another common practice is to use roles. You may specific a directory/controller for specific group of user called Role by adding the permitted role like this as an attribute above the controller:
[Authorize(Roles = "Admin")]
See this visual studio administration tool to create sample users and roles with built-in web interface.
You may also want to use sitemap to arrange your pages and menu link with show/hide menu based on current user role. Use this mvcsitemap to add security trimming features in ASP.NET MVC sitemap.
In some cases there happens to be a custom authentication instead of standard forms based (common case for enterprise level applications).
In this case I would recommend manually managing returnUrl parameter in the querystring. Login page reads this URL and redirects back after successful authentication.
Here is my issue. I have an ASPX web site and I have code in there to redirect from the login page with the call to "FormsAuthentication.RedirectFromLoginPage(username, false);" This sends the user from the root website folder to 'website/Admin/'. I have a 'default.aspx' page in 'website/Admin/' and the call to redirect works on a previous version of the website we have running currently, but the one that I am updating on a separate test server is not working. It gives me the error "Directory Listing Denied. This Virtual Directory does not allow contents to be listed." I have this in the config file:
<authorization>
<allow users="*" />
</authorization>
under the "authentication" option and...
<location path="Admin">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
for the location of Admin.
Also, there is no difference in the code between the web.config, Login.aspx, or the default.aspx files on the current server and the one on the test server, so I am confused as to why the redirect will not work on both. It even works in the Visual Studio server environment, for which the code is also identical.
Any suggestions and help is appreciated.
Directory Listing Denied is an IIS error, stating that directory browsing on the server isn't allowed. If you see this, it means when browsing to Website/Admin, the server isn't finding any expected default documents and is then trying to show you the file directory through the browser (expected behavior). IIS is set to not allow this in your case (which is a good thing).
Can you contact the server admins and ask them to verify the default documents for the website, and add Default.aspx to the list? If not, at least find out what the default file names are in the site setup, and name your root page based on that.
I think by default IIS uses Default.htm and maybe one other. Even when registering asp.net with IIS, I don't believe Default.aspx is added. It has to be done manually.