Role based authentication setting to defaultUrl in web.config in asp.net - c#

My application contains the roles "Admin" and "Users". How can I provide web.config setting for "users" with one default URL & "admin" with another default URL in web.config file.
My current web.config file code :
<authentication mode="Forms">
<forms defaultUrl="/Welcome.aspx" loginUrl="/LogIn.aspx" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
My aspx.cs code under login with condition :
if (res =="USER")
{
Details det = new Details();
int id = det.UserId(Email, Passwor);
Label2.Text = id.ToString();
Session["ID"] = Label2.Text;
string name = det.UserName(Email, Passwor);
Label3.Text = name;
Session["Name"] = Label3.Text;
Session["Role"] = TextBox1.Text;
Response.Redirect("Welcome.aspx");
}
if (res =="ADMIN")
{
FormsAuthentication.GetRedirectUrl(Email,true);
//Response.Redirect("admin_page.aspx");
}

Related

.net application basic authentication [duplicate]

This question already has answers here:
How to create asp.net web page with basic authentication
(1 answer)
Simplest way to add Basic authentication to web.config with user/pass
(1 answer)
Closed 2 years ago.
I want to implement a basic authentication in .net. So here i dont want an aspx page.
I only need web.config file and that should ask me for username and password( if i am not wrong we can have browser asking for username and password.)
Currently i have the below code which needs login.aspx page which i want to remove.
<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
<compilation debug="false" />
<authentication mode="Forms">
<forms>
<credentials passwordFormat="Clear">
<user name="abc" password="abc#123" />
</credentials>
</forms>
</authentication>
<!-- Unless specified in a sub-folder's Web.config file,
any user can access any resource in the site -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
<add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
<remove name="UrlAuthorization" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
</modules>
</system.webServer>
</configuration>
This isn't done in your application.
This is done in IIS, where you enable basic authentication and disable anonymous authentication.
But if you insist on doing it in code, you can add a HTTP-module, where you can check for basic authentication yourselfs.
E.g.
class SurroundingClass
{
public void ProcessRequest(HttpContext context)
{
if (!Authenticate(context))
{
context.Response.Status = "401 Unauthorized";
context.Response.StatusCode = 401;
context.Response.AddHeader("WWW-Authenticate", "Basic");
// // context.CompleteRequest();
context.Response.Flush();
context.Response.End();
return;
}
} // ProcessRequest
private static string[] ParseAuthHeader(string authHeader)
{
// Check if this is a Basic Auth header
if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic"))
return null;
// Pull out the Credentials with are seperated by ':' and Base64 encoded
string base64Credentials = authHeader.Substring(6);
string[] credentials = System.Text.Encoding.ASCII.GetString(System.Convert.FromBase64String(base64Credentials)).Split(':');
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0]))
return null;
return credentials;
} // ParseAuthHeader
private static bool TryGetPrincipal(string[] creds, ref System.Security.Principal.IPrincipal principal)
{
if (creds[0] == "Administrator" && creds[1] == "SecurePassword")
{
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("Administrator"), new string[] { "Administrator", "User" });
return true;
}
else if (creds[0] == "JoeBlogs" && creds[1] == "Password")
{
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("JoeBlogs"), new string[] { "User" });
return true;
}
else if (!string.IsNullOrEmpty(creds[0]) && !string.IsNullOrEmpty(creds[1]))
{
// GenericPrincipal(GenericIdentity identity, string[] Roles)
principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(creds[0]), new string[] { "Administrator", "User" });
return true;
}
else
principal = null;
return false;
} // TryGetPrincipal
// http://blogs.msdn.com/b/odatateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx
public static bool Authenticate(HttpContext context)
{
// DANGER: On the developer system, we need to be able to test it without SSL certificate
// If Not context.Request.IsSecureConnection Then
// Return False
// End If
string authHeader = context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authHeader))
return false;
string[] credentials = ParseAuthHeader(authHeader);
System.Console.WriteLine(credentials);
System.Security.Principal.IPrincipal principal = null;
if (TryGetPrincipal(credentials, ref principal))
{
HttpContext.Current.User = principal;
return true;
}
return false;
} // Authenticate
}

Issue with remember me in asp mvc membership

I have https website and I am using membership for logins and
my code in controller:
int timeout = rememberme ? 2880 : 2; // Timeout in minutes,525600 = 365 days
var ticket = new FormsAuthenticationTicket(username, rememberme, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);//My Line
Response.Cookies.Add(cookie);
string returnurl = FormsAuthentication.GetRedirectUrl(username, rememberme);
if (string.IsNullOrEmpty(returnurl)) returnurl = "/Panel/Login";
if (string.IsNullOrEmpty(returnurl)) returnurl = "/Panel/Login";
if (rol == "User")
return Redirect("/Panel/Dashboard");
else if (rol == "Admin")
return Redirect("/Panel/DashboardAdmin");
return View();
and in we.config:
<httpRuntime targetFramework="4.6.2" executionTimeout="100000000" maxRequestLength="2147483647" />
<authentication mode="Forms">
<forms loginUrl="~/Panel/Login" requireSSL="true" slidingExpiration="true" />
</authentication>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
so its just keep login for 2 minutes and remember me is not working
what should I do?
we should add this to system.web in web.config file
an U can generate this key in iis but if U can access to iis U can use this code
<machineKey
decryptionKey="1513F567EE75F7FB5AC0AC4D79E1D9F25430E3E2F1BCDD3370BCFC4EFC97A541"
validationKey="32CBA563F26041EE5B5FE9581076C40618DCC1218F5F447634EDE8624508A129"
decryption="AES"
validation="SHA1"
/>

Asp.Net Role Based Authentication?

I want to redirect user based upon role.I can do it without using Forms Authentication but I want to do it with forms authentication. Following is my code:
Web.Config
<authentication mode="Forms">
<forms loginUrl="Forms/Login.aspx" defaultUrl="Member/Home.aspx">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Login.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
members.memberEmail = txtEmail.Text;
members.memberPassword = operation.EncodePasswordToBase64(txtPassword.Text);
DataSet ds = operation.GetUsers(members);
if (ds != null)
{
int role = int.Parse(ds.Tables[0].Rows[0]["memberType"].ToString());
if (role == 2)
{
Response.Redirect("../Member/Home.aspx");
}
else if(role == 1)
{
Response.Redirect("../Admin/Home.aspx");
}
}
}
Here GetUsers function giving back the Dataset of members and I am checking role from DataSet and redirecting the user to respective home page. I am trying to accomplish same thing using forms authentication:
I have enabled the role manager in web config:
<roleManager enabled="true">
</roleManager>
I know, I am doing wrong. Can anyone guide me?

unable to redirect to login page after using forms authentication

Before applying forms authentication on login page I am able to redirect to login and registration page from website's homepage but after applying form authentication on login page, whenever I tried to redirect to login page it shows me error(below image):
I can't find out where I am making mistake. I have posted .cs code of login page and web.config file . have a look over it. show me where I am making mistake and what is the solution.
LoginPage.aspx.cs :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Security;
public partial class Registration_LoginPage : System.Web.UI.Page
{
Code code = new Code();
SqlConnection con;
SqlCommand cmd;
bool flag = true;
public Registration_LoginPage()
{
con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
cmd = new SqlCommand();
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
Response.Cache.SetNoServerCaching();
Response.Cache.SetNoStore();
}
if(User.Identity.Name !=String.Empty)
{
FormsAuthentication.RedirectFromLoginPage(User.Identity.Name, false);
}
}
protected void btnLogIn_Click(object sender, EventArgs e)
{
// String encryptedPassword = code.encrypt(Request.Form["password"]);
try
{
con.Open();
cmd.CommandText = "select * from [Users]";
cmd.Connection = con;
SqlDataReader rd = cmd.ExecuteReader();
if (Request.Form["username"] == "admin" && Request.Form["password"] == "admin")
{
Session["Username"] = Request.Form["username"];
Response.Redirect("/AdminHome/AdminMPage.aspx");
}
else
{
while (rd.Read())
{
if (rd["UserName"].ToString() == Request.Form["username"] && rd["Password"].ToString() == Request.Form["password"])
{
Session["Username"] = rd["UserName"];
flag = false;
break;
}
}
if (flag == true)
lblMsg.Text = "Username and password invalid";
else
{
if (rd["Role"].ToString() == "Student")
// Response.Redirect("Student.aspx");
FormsAuthentication.RedirectFromLoginPage(rd["Role"].ToString(), false);
/* else
Response.Redirect("Teacher.aspx"); */
if (rd["Role"].ToString() == "Teacher")
FormsAuthentication.RedirectFromLoginPage(rd["Role"].ToString(), false);
}
}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
}
web.config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="/Registration/LoginPage.aspx">
</forms>
</authentication>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<location path="FIRST PAGE">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="Registration">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="AdminHome">
<system.web>
<authorization>
<allow users="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="Student">
<system.web>
<authorization>
<allow roles="Student"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="Teacher">
<system.web>
<authorization>
<allow roles="Teacher"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
</appSettings>
</configuration>
Remember that using FormsAuthentication.RedirectFromLoginPage requires Username and persistence, so rd["Role"].ToString() won't work.
Follow this example as it will give you the quick solution.
FormsAuthentication.RedirectFromLoginPage to a custom page

trying to get the username used to sign into the website

I'm using the following code to check the user's credentials and if successful I put them to make-request.aspx, but on make-request.aspx I want to check the value of the username they entered so I can show certain content.
Here's the authentication code:
foreach (string key in ConfigurationSettings.AppSettings.Keys)
{
dominName = key.Contains("DirectoryDomain") ? ConfigurationSettings.AppSettings[key] : dominName;
adPath = key.Contains("DirectoryPath") ? ConfigurationSettings.AppSettings[key] : adPath;
if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))
{
if (true == AuthenticateUser(dominName, userName, txtPassword.Text,adPath, out strError))
{
Response.Redirect("../make-request.aspx");// Authenticated user redirects to default.aspx
}
dominName = string.Empty;
adPath = string.Empty;
if (String.IsNullOrEmpty(strError)) break;
}
Everything works fine but I'm not sure how to get the username they entered into the form. Here's code that I've tried that is getting username of the machine username -- I think. Any help would be appreciated!
I've tried all three of these:
//string userName = Environment.UserName;
string userName = HttpContext.Current.User.Identity.Name;
//string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Here's the authentication/auth section of web.config:
<authentication mode="Windows" />
<authorization>
<allow users="*" />
<!--<deny users="*"/>-->
</authorization>
You are authenticating the user but not setting forms authentication cookie. Here's what you need to do:
FormsAuthentication.SetAuthCookie(userName, false);
Response.Redirect("../make-request.aspx");
Also make sure you have proper authentication/authorization set in your web.config. If you are not sure if it is setup correctly, share it here so we can take a look.
Set FormsAuthentication as below:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
The HttpContext.Current.User.Identity.Name will work as long as the user is currently logged in when it is ran. In one of my sites, I use the following (written in VB):
Dim u As MembershipUser = Membership.GetUser(Membership.GetUserNameByEmail(HttpContext.Current.User.Identity.Name))
Tip: You can test if the user is already logged in by checking the value of HttpContext.Current.User.Identity.IsAuthenticated.
However . . .
. . . Using the current HTTP context is only necessary in content pages or web APIs. Alternatively, you can use MembershipUser u = Membership.GetUser(); from the master page, and then use u.Username to retrieve the username or u.ProviderUserKey to retrieve the GUID of the user.
If Session Is Nothing OrElse Session(Current_User) Is Nothing Then
udtGeneral = GetdoGeneralInstance()
susername = Request.ServerVariables("LOGON_USER").Split("\")(1).ToString()
'Either of these work i believe
susername = Request.ServerVariables(7).Split("\")(1).ToString()
'Dim susername1 = Request.Browser.Capabilities("extra").ToString.Split(";")(14).ToString.Split(":")(1).ToString
Session("ipAddress") = Request.ServerVariables("REMOTE_ADDR").ToString()
End If

Categories