Forms Authentication for different roles? - c#

I am developing a website in which I'm using forms authentication.
We have 2 log in pages: one for user, another for admin.
I added this code into webconfig file for user.
<forms loginUrl="Login.aspx" defaultUrl="Home.aspx" >
I am using this code for user side when user successfully logged in.
FormsAuthentication.RedirectFromLoginPage (UserName.Text, chkPersistCookie.Checked)
I am not using the default user membership database. I have my own database in SQL Server 2005.
I want same thing for admin, but the default url is Admin.aspx & login url is adminlogin.aspx for admin.
How can i assign in web config file for admin? Is it the right way to do that or any one have some better concept for that?

I used This line of code and this worked for me.
FormsAuthentication.SetAuthCookie(txtUser.Text, true);
Response.Redirect("Admin.aspx");

Putting admin files to a folder and creating a web.config file in it, is an option. You can probably override the config rules there.

Related

Accessing Directory with currently logged in User

I have a website that is using Windows authentication that calls an API. The API has the Authorize attribute:
[Authorize(Roles = #"myrole.local\role")]
The API then makes a call to a method in my business layer that does this:
string [] directories = Directory.GetDirectories("\\\\server\\folder\\folder2");
When running locally this works as intended. When my IT ops guy checks the audit logs, he sees that my login has accessed that folder.
Now when I deploy my website to our development environment, it no longer works (we get an "access denied" error for that folder). So we looked into it and found that the user trying to access the folder was our server (something like server$) tried to access folder and failed.
So my question is: how do I access the folder with the current user that is logged in? I have looked this up here on Stack Overflow and I see impersonation comes up a lot. I have tried this example with no luck:
public static List<DirectoryName> GetDirectories(IPrincipal user)
{
string[] directories;
using (WindowsImpersonationContext impersonationContext = ((WindowsIdentity)user.Identity).Impersonate())
{
//Insert your code that runs under the security context of the authenticating user here.
directories = Directory.GetDirectories("\\\\server\\folder\\");
}
}
I am still denied access.
I have the user that is logged in though, so I know I can 'see' them, but the folder I am trying to access says it's the server.
Does anyone know how to get around this? Am I missing something?
P.S. I have created the website with IIS and have set both the API and website to use windows authentication. (anon = false;); but still it says the server is trying to access the folder.
P.P.S. In the web.config for the API, I have these tags as well:
<system.web>
<!-- ... -->
<authentication mode="Windows"/>
<authorization>
<allow roles="group.local\group" />
</authorization>
</system.web>
Edit: So we were able to access the folder path with the logged in user but only when going to the website on the server.
If we go to the website off our dev server we will then get an access denied error. Also there is no audit line when this fails.
Hopefully this edit provides more insight.

Is this the correct way for ASP.NET web application to do authentication?

ASP.NET Web Forms applications.
I checked our company's legacy code, the way they do login is like this:
when user is validated against database with (username, password), they set a session:
Session["authenticated"] = "true";
Every page other than login.aspx is inherited from a class named SecurePage. In SecurePage's OnInit() method, it checks
if (Session["authenticated"] != null)
if true, means authenticated, otherwise means not. So basically the way to do authentication is to see if there is a session named authenticated.
This seems the most crude and intuitive way of doing authentication... I want to ask: is this safe?
Another thing I feel strange is that in the web.config, they have this:
<authentication mode="Windows" />
Shouldn't it be
<authentication mode="Forms" />
since these are web applications? Users credentials are stored in database and these users are outside clients (not internal users).
A slight different version also does this after user is validated against database:
FormsAuthentication.SetAuthCookie( username, true );
what does this do? Besides this statement in login.aspx, I don't see any other pages have any code related to auth cookie. Do we need to set auth cookie by ourselves in code or does .NET framework handle this for us already?
Still another version have the following:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(login, false, 60);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
what does this do? Do we need to set this cookie by ourselves in code? or does .NET framework handle this for us already?
These web appliations were developed a long time ago, though I am not sure when. I suspect it is .NET 1.0 era? From my understanding since .NET 2.0,
it has this ASP.NET membership thing, and we can just use <authentication> and <authorization> tags in web.config (and subfolder web.config) to achieve the goal of authentication and authorization. Isn't it? Can anyone give me a history of ASP.NET framework authentiation mechanism? (membership -> simple memebership -> Identity?)
<authentication mode="Windows" />
Above should be used mostly in intranet website, because it's like saying use the computer(windows pc) authentication to access the resource. However, this will never work, since inherited class has a method to validate session key value for a login.
You should make sure that the code redirects user to login page in case the session key is not found. That means, in the else section of below code, you should take users to login page to try again. Which I am sure is happening.
if (Session["authenticated"] != null)
{ /*user is authenticated*/ }else{ /*redirect to login*/ }
Its is recommended to use <authentication mode="Forms" /> if the website is accessible over the internet. Other benefit of using this setting is that you can set default and login page.
Finally, FormsAuthenticationTicket is a class with property and values that are used when working with Forms authentication to identify authenticated users.
Read through msdn article to know more about asp.net membership.
https://msdn.microsoft.com/en-us/library/yh26yfzy%28v=vs.140%29.aspx

Retriveing Asp.net/C# values inside web.config

How to receive asp.net/C# variable values inside web.config?? Is there any way?
Under,
<identity impersonate="true" userName="hcltech\Loggedonusername" password="LoggedonUserPasswd" />
How to receive log in credentials inside web.config?..Please help
How to receive asp.net/C# variable values inside web.config?? Is there any way?
No, there is not.
There is no point in impersonating the user that is logged in already, because they are logged in already. Impersonation is for giving the current user the permissions of a different Windows user.

ASP.NET C# Authentication Autorization

I am as a study project developed a website in ASP.net. In my web.config file i have autheticaion mode as windows. and i am using an appsettings connection string to connect to my SQL2005 database.
Now i want to know what kind of authentication is this?
Is this windows? forms? or anonymous authentication?
I have user table in sql 2005 and my first screen is login page. Obviously this user table has login details like username and password which will be matched to user input.
I dont understand i have read so many post on authorization and authienticaion but please clear me on this. Thanks in advance.
You are currently using Windows authentication. Your Windows username and password is used to authenticate you to asp.net.
A login page writing to a user table would be asp.net forms authentication.
Note that sql server authentication is a totally separate issue. It is up to your code to authenticate against your database. When doing so, the connection string in web.config file can be used.
If you want customize your credentials of string connection in order to access your DataBase, you can use Integrated Security
or Trusted_Connection
When the value is true, the current credentials of the Windows account used for authentication.
Nota : in yur case i think that you can use FormsAuthentification (You have Windows Authentification)
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.80).aspx
Forms Authentification :
<authentication mode="Forms">
<forms loginUrl="~/login.aspx">
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
After your click
if (IsAuthenticatedValue) //You can adjust your condition
{
FormsAuthentication.RedirectFromLoginPage (.., ..);
}
else
{
Console.WriteLine("Invalid credentials. Please try again.");
}
Link : http://msdn.microsoft.com/fr-fr/library/xdt4thhy(v=vs.80).aspx
In addition to the other answer here:
Once the user is logged in, create a Session and store the fact they are logged in using that such as
Session["LoggedIn"] = true;
Session["Username"] = username;
Then check if they are logged in using your Code and authorise access to the page using that. So on page load if they logged in continue loading the page, else send them to the login page.
When you want to log the user off simply do Session.Clear();

Best approach to store login credentials for website

I have created a site in ASP.NET 3.5 & I have only 2 or 3 user login IDs who can login to the website.
What would be the best way to save these login details? Which of these approaches, or others, would be most suitable?
Using Forms Authentication, and saving credentials (username and password) in web.config
to create a text file in directory and modify it
Which approach is best from a security and maintenance perspective? What other approaches are suitable for a login system for ASP.NET?
Use the default ASP.NET Sql Membership Provider. The link will show you how to used it and get it configured.
Do you already have a database? If so, use forms authentication and ASP.NET membership like everyone says. It is real simple to integrate into your current database (assuming it's sql server - i don't know about others). I realize adding a DB for 2 or 3 users isn't always an option due to budget or whatever so you can use forms authentication and store the user in the web.config. I've done this in the past and it is very simple.
Your web.config will look like:
<authentication mode="Forms">
<forms loginUrl="Login.aspx">
<credentials passwordFormat="Clear">
<user name="myUser" password="password" />
</credentials>
</forms>
</authentication>
Then you can use the built in login controls. If you do it this way you need to implement the Autenticate event.
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
string UserName = Login1.UserName;
string Password = Login1.Password;
if (FormsAuthentication.Authenticate(UserName, Password))
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
Of course this isn't the most secure way to go about this, and you'll probably want to at least look at encrypting the credentials in the web.config, but it is simple and works when a database isn't an option.
With ASP.NET you can use some of the built-in/provided authentication providers that let you manage the users in a database and it uses proper guidelines like hashing passwords, etc. by default.
You could use ASP.NET membership. Even though you won't have many users, it handles all of the authentication details for you.

Categories