Prompting the user for login authentication - asp.net

ASP.NET: I have created a website with login authentication. Before the user can visit any of the pages in it he needs to login first. How do I prompt the user to login first before he can view any of the contents of the website?

The Examining ASP.NET's Membership, Roles, and Profile series is a good starting point. It covers all the security part of ASP.NET and your required stuff, Login before visiting the page via LoginUrl as your login page. starting doing this How To: Use Forms Authentication with SQL Server in ASP.NET 2.0
Some setting to be made in web.config and then handle of these things on code behind.
<forms name=".ASPXAUTH" loginUrl="login.aspx"
defaultUrl="default.aspx" protection="All" timeout="30" path="/"
requireSSL="false" slidingExpiration="true"
cookieless="UseDeviceProfile" domain=""
enableCrossAppRedirects="false">
<credentials passwordFormat="SHA1" />
</forms>
Add the following element under the element in the Web.config file. This allows all authenticated users to access your Web site.
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>`
code behind
if (Membership.ValidateUser(username, password))
{
// User has supplied valid credentials
// In the following method call, the second Boolean parameter
// determines whether a persistent authentication cookie
// is created.
FormsAuthentication.RedirectFromLoginPage(username, rememberMeIsChecked);
}
Reference:
Starting ASP.NET Forms Authentication
ASP.NET Authentication
Explained: Forms Authentication in ASP.NET 2.0

Try to do this in your web.config
If we want to deny access to anonymous users, configure the Authorization section in the following manner,
<configuration>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
For more info look here

This is huge subject to cover on posting code example here so I would recommend following steps.
Use asp.net mvc3, learn how membership provider work, customize it if to fit your needs, user role provider to assign users to specific groups which you will use to protect specific area of site.
Create roles and assign them to user and after that you can secure pages using decorated [Authorize] attributes or secure for selected users like this
[Authorize(Roles = "Admin, Super User")]
Use your web.config in configuration system.web section to indicate what membership and role provider is used in app.
This is short info, but I hope that you have concise mental picture now.

Related

Is IIS Form Authentication related anonymous authentication account?

Some resources (images) don't appear when I visit the main page after login (using form authentication)
However, setting the attribute of anonymous authentication to 'application pool id' in iis manager works
what windows account is used for form authentication in iis?
Only the login Page need anonymous authorization access. It sounds like you didn't set anonymous authentication correctly.
When we implement form authentication in IIS, Both form authentication and anonymous authentication are enabled side-by-side. Then we will create allow auth rule for all user and deny anonymous user in site level.
<authentication mode="Forms">
<forms name=".MyCookie" loginUrl="Login" protection="All" timeout="60" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Secondly, we need to create a authorization rule to allow anonymous access to login page.
<location path="Login">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
When you pass the form authentication, IIS will send a form authentication cookie with the username which is decided by your application. It can be a key in appsetting or a username from database.
1.
FormsAuthentication.SetAuthCookie(UserInfo.UserName, false, FormsAuthentication.FormsCookiePath);
2.
FormsAuthenticationTicket
3.
FormsAuthentication.RedirectFromLoginPage(UserInfo.UserName, false);
You need to make sure the auth_user and application pool identity have permission to access the image sources.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio

Combining Forms auth and OpenIdConnect auth in the same WebForms app

I have a legacy multi tenancy WebForms app where users authenticate using forms authentication. We are migrating the auth system to IdentityServer4 but can't do it all at once, so we want to gradually introduce this to our tenants. This means we need to run the WebForms app with both Forms Auth and the new OpenIdConnect Auth at the same time.
My problem is that whenever I run HttpContext.Current.GetOwinContext().Authentication.Challenge(), I'm redirected to Login.aspx because of this:
<authentication mode="Forms">
<forms name="AuthCookieName" loginUrl="~/Login.aspx" timeout="60" protection="All" requireSSL="true" enableCrossAppRedirects="true" />
</authentication>
What I want is that whenever someone navigates to /OIDC.aspx, the challenge will redirect the user to IdentityServer as configured using OWIN. For all other requests, the existing Forms auth configuration can handle the authentication.
Is this at all possible?
I managed to prevent the unwanted redirect by setting the Response.SuppressFormsAuthenticationRedirect flag when invoking the authentication challenge, e.g.:
HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
HttpContext.Current.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/Home.aspx" });
HttpContext.Current.GetOwinContext().Authentication.Challenge() will do an authentication challenge against the default security scheme - in this case, yours is Forms Auth. You can pass in a string denoting what security scheme(s) to use in the challenge, like so HttpContext.Current.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType)
OIDC uses Callback Url. This webform security restricts this url and redirects to login page. Allowing access to that call back url using location tag worked for me.
<authentication mode="Forms">
<forms loginUrl="default.aspx" name=".CLFORMSAUTH" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
<location path="authorization-code/callback">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>

How to get the windows login user on asp web page?

I wonder if it is possible for an official way or hack to retrieve the windows login of the user currently logged on a asp web page with option "allow anonymous users" ? Or using imported windows dll perhaps ?
I know that normally with the "deny anonymous users" I can easily retrieve the login windows. But for some special reason I would like to retrieve the windows login and accept anonymous users. So that if the windows login is a user in my database I redirects to another web page.
I have ckecked that: (but windowsLogin == always empty)
ASP- C#
string windowsLogin = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;
string windowsLogin = System.Threading.Thread.CurrentPrincipal.Identity.Name;
string windowsLogin = System.Net.CredentialCache.DefaultCredentials.ToString();
string windowsLogin = Request.ServerVariables["LOGON_USER"].ToString();
Web.config
<authorization>
<deny users ="?" /><!-- Deny acces to anonymous users-->
<allow users ="*" /><!-- Allow acces to every users-->
</authorization>
<identity impersonate="true"/>
<authentication mode="Forms">
<forms loginUrl="./WebLogin.aspx" defaultUrl="./default.aspx" timeout="12" path="/" name=".ASPXFORMSAUTH" slidingExpiration="true" />
</authentication>
You'll need to allow anonymous users, it seems, and you might want to try Windows authentication.
<authorization>
<allow users ="*" /><!-- Allow acces to every user and do not deny anonymous -->
</authorization>
<authentication mode="Windows" />
It seems ServerVariables have been depreciated for C# in some instances.
If so, you'll need to do it this way:
string login = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
If you really want to use ServerVariables, keep in mind they are CaSe Sensitive in C#. The correct casing is almost always UPPER, and here is the list of them:
List of ServerVariables

How can I have ASP.NET automatically redirect non-logged in Forms users to the login page?

I have an ASP.NET website.
I want users who are not logged in to be automatically (re)directed to the login page, for example,
~/Account/Login.aspx
As it is now, users are able to visit pages (for example, default.aspx) without being logged in.
Note: I am operating on the (perhaps incorrect) assumption that ASP.NET has its own authentication cycle that happens behind my back before every (and any) page loads.
Update #asawyer provided a link that, while not helping to answer the question, did provide a pretty graphic:
Well, what have you tried?
I have a web.config file that enables Forms authentication:
<?xml version="1.0"?>
...
<configuration>
...
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" name=".ASPXFORMSAUTH" slidingExpiration="true"/>
</authentication>
...
</system.web>
...
</configuration>
When i browse to the "default" page, I am able to view it, for example,
GET http://localhost:53149/WebSite/ HTTP/1.1
Host: localhost:53149
And I'm get the page contents:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
In other words, rather than being forced to login to the web-site, I am not being forced to log in to the web-site.
It might be related to the fact that my browser is running locally to the web-server; but I'm using Forms, not Windows (and not Passport and not None) authentication.
Bonus Reading
An Overview of Forms Authentication (C#)
MSDN: Forms Authentication Provider
MSDN: ASP.NET Web Application Security
ASP.NET Forms Authentication
Require the user to log in to view a document using ASP.NET
Protect some pages from direct access in ASP.NET
FormsAuthentication Class
I found the answer.
Question: How do I automatically redirect non-logged in users to the login page?
Answer: Deny anonymous users access
Longer Explanation
In order to automatically redirect non-logged in users to login page, you need to deny anonymous access to "all" pages. This is done in the site's web.config file:
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
...
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
The special ? token is used to represent anonymous users.
This, when combined with telling Forms authentication where the "Login" page is:
<?xml version="1.0"?>
<configuration>
<system.web>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
means that any any anonymous users will be automatically redirected to the login page.
A question that seems to never have been asked before gets answered, and everybody lives.
If you wish to force for all pages all used to be first logged in, you can capture the authentication request on global.asax and make this programmatically as:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// This is the page
string cTheFile = HttpContext.Current.Request.Path;
// Check if I am all ready on login page to avoid crash
if (!cTheFile.EndsWith("login.aspx"))
{
// Extract the form's authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
// If not logged in
if (null == authCookie)
// Alternative way of checking:
// if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("/login.aspx", true);
Response.End();
return;
}
}
}
This code is called on every page and checks all pages on your site.
I know it's many years later, but if anyone finds themself here you may be missing this bit in the webconfig. Within the tag you need to add this:
<location path="SecurePage.aspx">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
This tells the site that SecurePage.aspx requries the user to be logged in. This is how I've been doing it for a few years now
Add this to you web.config
<system.web>
// ...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx"
name=".ASPXFORMSAUTH"
slidingExpiration="true" />
</authentication>
</system.web>

Redirect users to logon page only if not authonticated in asp.net MVC

NET MVC project i have following tag in in web.config file
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
This causes even the authenticated users but unauthorized resource requested users to redirect to logon page. but i need only to redirect this page if user try to access unauthorized page and not already authenticated(logged on) and redirect to custom page.
Is there easy way to do this without writing custom action filter?
All that this line does in web.config is to simply define the timeout of the authentication cookie and the login url. It is your code that decides which parts of the site are authenticated or no, by for example decorating your controllers and/or actions with the [Authorize] attribute.
please check your "authorization" setting in web.config file. It should be somewhat
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
also when user authenticates successfully make sure you call
FormsAuthentication.SetAuthCookie(<username>, false);

Resources