I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.
Related
Thank you for providing help. I have a site that can authenticate with Active Directory Federated Services for Single Sign On. Currently, the way my site works is that, by default, when a user hits my site, my code attempts to log then into SSO (I use the OWIN library for this). If the user is not on our network, it fails to authenticate, and they are redirected to my companies login page, where they can provide their company credentials.
I would like to change this behavior, though. Instead, when the user hits my page, if they authenticate, it should continue as normal and they should be redirected to my site. But, if they do not authenticate, I do not want them redirected to our login page. instead, I want them to be redirected back to my site, where my code will determine what they can and cannot do on the site. I then would want to provide a link, so that they could decide to go to the login page.
I want this behavior because the majority of users of this site will not be a part of the companies network and will not be able to authenticate. SO, they should, by default, just see our home page. But, there may be times when a company member might be working from home, so wont be on our network to auto authenticate. In this case, they would then use the link that sends them to the Azure login page.
Here is the code that I am currently using (site is ASP.net, form web page (not MVC)):
Startup.Auth.vb:
Partial Public Class Startup
Dim appSettings = ConfigurationManager.AppSettings
Private realm As String
Private aadInstance As String
Private tenant As String
Private metadata As String
Private authority As String
Public Sub ConfigureAuth(app As IAppBuilder)
Try
Dim appSettings = ConfigurationManager.AppSettings
If (appSettings("releaseVersion") = "DEBUG") Then
realm = ConfigurationManager.AppSettings("test_ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("test_ida:AADInstance")
tenant = ConfigurationManager.AppSettings("test_ida:Tenant")
ElseIf (appSettings("releaseVersion") = "PROD") Then
realm = ConfigurationManager.AppSettings("ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("ida:AADInstance")
tenant = ConfigurationManager.AppSettings("ida:Tenant")
End If
metadata = String.Format("{0}/FederationMetadata/2007-06/FederationMetadata.xml", aadInstance)
authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
Dim authOption As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions()
Dim fn = Function(context)
context.HandleResponse()
context.Response.Redirect("Home/Error?message=" + context.Exception.Message)
Return Task.FromResult(0)
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
}
Dim auth_opt As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata,
.Notifications = auth_not
}
If (Not auth_opt.Wtrealm Is Nothing) Then
app.UseWsFederationAuthentication(auth_opt)
Else
End If
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
Then, on my Default.aspx.vb page load event, I do this:
If (Not Request.IsAuthenticated) Then
Try
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, WsFederationAuthenticationDefaults.AuthenticationType)
Catch ex As Exception
Throw ex
End Try
End If
The problem is, I do not know how to attempt to authenticate the user, determine if they are authenticated, and redirect them accordingly. Any help would be greatly appreciated.
thanks
There is not solid/correct way how to check if anonymous user is inside your network(or I am not aware of one). Possible way is to check IP address (range) users inside your network have publicly on the Internet. This is something you can check with network administrator(s). They may tell you public IP address (range).
Once you know public IP address (range) you can check incoming request to compare if the request is coming from the known reange of IP address (range) inside RedirectToIdentityProvider function.
Dim redirectToIdentityProvider = Function(context)
Dim isCompanyNetworkUser = companyIPAddress == context.Request.RemoteIpAddress
' Or relevant check for range
' Dim isCompanyNetworkUser = (companyIPAddressRangeStart < context.Request.RemoteIpAddress AndAlso companyIPAddressRangeEnd > context.Request.RemoteIpAddress
If Not isCompanyNetworkUser Then
context.State = NotificationResultState.Skipped
context.HandleResponse()
End If
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
.RedirectToIdentityProvider = redirectToIdentityProvider
}
You may want to tweak it a bit as I didn't try it, but may point you to right direction.
Sorry to not providing full code example, but in my opinion :
You may try to bypass the sign-in page prompts, take a look here, which explain you how to :
bypass the sign-in page prompts by adding your company’s existing federated domain name to the end of the Windows Azure Management Portal URL
You may also find usefull information relative to Azure Active Directory Pass-through Authentication which allow that:
When users sign in using Azure AD, this feature validates users' passwords directly against your on-premises Active Directory.
You may also make appear your website as an "application" then added this app to your Azure Active Directory application gallery. then Managing single sign-on for enterprise apps
I found finally that this question may be relative to your question.
I have this project I am working on for an assignment, and I have a question working with ASP.NET and SQL Server. I have a login page that kinda works, but there are two tables that I need to get data from - users (subscribers) and admin page but am unsure how to access both of them as I can only access one.
public void login(Object src,EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("SELECT * FROM subscribers WHERE Email = #Email AND Password = #Password", connection);
command.Parameters.AddWithValue("#Email", loginName.Text);
command.Parameters.AddWithValue("#Password", loginPass.Text);
//command = new SqlCommand("SELECT * FROM admin WHERE Email =#Email and Password = #Password", connection);
//command.Parameters.AddWithValue("#Email", loginName.Text);
//command.Parameters.AddWithValue("#Password", loginPass.Text);
reader = command.ExecuteReader();
I commented out the admin part because when I include it, only admin username and password is accepted and not subscribers. What would I need to do to fix this?
The "admin part" causes you to only get records from the admin table because you're destroying and recreating your SqlCommand object. You'll need to create a new command in a different variable and read from it separately. There are ways to get multiple recordsets in the same call but I don't recommend it in this case.
That out of the way... Normally I'd expect to see a single users table with permissions/roles granted elsewhere. Consider something like the out of the box ASP.NET membership provider to take care of these implementation details for you:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider
I'm using ASP.NET Membership in order to manage a website users. But without using the specific 'Login Controls'. Actually, just applying Membership class methods in order to Create a user account and also to User login.
On the other hand, there is a LoginView control in Site.Master which is responsible to 'Welcome Username' task.
The problem is that, the LoginView control isn't updated after creating new account or any login.
Do I have to Definitely use the specific login controls?
----Also, I have set the Login Button CommandName to 'Login'!
----Should I set something like that for Create User Button?
I would appreciate any help...
The following is my code for login:
if (!Membership.ValidateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text)))
{
lblResult.Text = "Invalid user name and password.";
lblResult.Visible = true;
}
else
{
Response.Redirect("~/Default.aspx");
}
And here the registration code:
MembershipCreateStatus statusUser;
try
{
Membership.CreateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text), HttpUtility.HtmlEncode(txtEmail.Text), ddlSexQues.SelectedValue != "-1" ? ddlSexQues.Text : string.Empty, txtSecAnsw.Text == string.Empty ? string.Empty : txtSecAnsw.Text, true, out statusUser);
txtEmail.Text = string.Empty;
txtPass.Text = string.Empty;
txtRepass.Text = string.Empty;
txtSecAnsw.Text = string.Empty;
txtUserName.Text = string.Empty;
ddlSexQues.SelectedValue = "-1";
lblRsl.ForeColor = Color.Green;
lblRsl.Text = "حساب کاربری شما با موفقیت ایجاد شد.";
lblRsl.Visible = true;
}
catch (MembershipCreateUserException error)
{
lblRsl.Text = GetErrorMessage(error.StatusCode);
lblRsl.Visible = true;
}
If you're using your own login code, you'll need to persist the user's authentication information, for instance by adding a cookie to the response. The built-in controls do this automatically.
I'm assuming you're using Forms-based authentication. There's a reference to the .NET security class for Forms auth here, which details what options are available to you:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
Look at the SetAuthCookie and RedirectFromLoginPage methods in particular.
As far as I'm aware, the CommandName property is for distinguishing between Button controls in code. As you're using your own methods to handle user creation, I don't think you need to add it to your own control. More here:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!
If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....
http://msdn.microsoft.com/en-us/library/ff647396.aspx
How to Dispaly the username on all aspx pages....?
Can any one help me in this context.....
am thinking that by using "session object" we can able to do this...bt am not sure
Can any send the code or links
Assuming that you have a mechanism you can use to obtain the current user's username, you could fetch that and add code to your master page(s) to display the name. There's not really much more that can be said from your question. (Ask a vague question, get a vague answer.)
And also, if you aren't using master pages, you should be using master pages.
You can use a master page if you want to display the username on all pages.
Username can be stored in a cookie, session, etc.
Code sample:
lblUsername.Text = Session["Username"]
System.Security.Principal.IPrincipal user;
user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity;
identity = user.Identity;
lblUserName.Text = identity.Name.Substring(identity.Name.IndexOf(#"\") + 1); ToString();
In First Page (Login page), store the value in Session
Session["Username"] = txtusername.text;
And rest of the pages, where you want to display the UserName
lblUser.Text = Session["Username"].Tostring();
For Logout
Session["Username"] = null;