I setup a login control to use on my web application and having issues validating the users. I created the membership tables in my own database in sql server 2008 using a suggestion on another site. Then I opted to just use forms authentication and created two users in the WSAT and thought that this would work fine. But it returns false for all users including the two I created. Why this is so I am not sure and if I were to use the sql database tables how would I do this?
<authentication mode="Forms">
</authentication>
<authorization>
<allow users="boy"/>
<allow users="girl"/>
</authorization>
<roleManager enabled="true" />
code behind login:
If Page.IsValid then
If username <>"" and password <>"" then
If FormsAuthentication.Authenticate(username,passwprd) = False then
Return false
else
response.redirect("~/default.aspx")
End If
End If
End If
You need to configure your web.config to use the MembershipProvider.
Take a look here for more info. Are you trying to use the SqlMembershipProvider?
To authenticate using MembershipProvider use the Login user control or you can create your own and call the following methods:
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie);
}
Related
I have created a Login page where users must provide username and password to have access to some specific resources, where they can upload images, or just edit some description about themselves.
My web.config file looks like this:
<authentication mode="Forms">
<forms loginUrl="Secure/Login.aspx" defaultUrl="index.aspx" name=".ASPXFORMSAUTH" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="Secure">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
So when the user has typed in the username and pw, he is redirected to the index.aspx page.
Depending wether the user is logged in or not, the index.aspx should show or hide some stuff.
This is how I check if he is logged in:
bool isLoggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
if (isLoggedIn)
{
placeHolder2.Visible = true;
...
}
Now the problem is that the: HttpContext.Current.User.Identity.IsAuthenticated; ALWAYS returns true, so unauthorised people will be seeing the stuff that should be hidden.
I am not sure about the: HttpContext.Current.User.Identity.IsAuthenticated;
I just googled "How to check if user is logged in", and suggestions were the:
HttpContext.Current.User.Identity.IsAuthenticated;
I want only the people that are logged in to view the private stuff. How do I go about this? How do I make the: HttpContext.Current.User.Identity.IsAuthenticated only return true when the user is logged in?
Thanks
if (Request.IsAuthenticated) {.....}
edit based on some comments
Authenticated via "Forms", check here
HttpContext.Current.User.Identity.IsAuthenticated // will be "Forms" if using forms based auth
// "Negotiate" is using windows integrated
// etc
If using .net 4.5 and you wanted "SET" user claims.
The ClaimsPrincipal is recommended reading
bool isLoggedIn = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
My coding is
bool val1 = (System.Web.HttpContext.Current.User != null) &&
(System.Web.HttpContext.Current.User.Identity.IsAuthenticated) &&
(System.Web.HttpContext.Current.User.Identity.AuthenticationType.ToString() == "Forms");
for identifying the users with domain login and logged in form
I have a forms based application. The application is standard ASP.Net wizard generated with login controls. The root's web.config appears to be in order for forms based authentication. I did have to change the <roleManager> element to use type="System.Web.Security.SqlRoleProvider" (rather than a Windows token) per How To: Use Role Manager in ASP.NET.
I have setup three roles - Administrators, Engineers, Customers. There are three users - admin (administrator), eddie (engineer), and cathy (customer). I have verified the users and their roles using ASP.Net Configuration Tool.
Each role has its own directory on disk, and each role has its own collection of ASPX files and 'landing page'. Each directory has a web.config to limit access to the role in question. For example:
<location path="~/Engineers">
<system.web>
<authorization>
<allow roles="Engineers" />
<deny users="*"/>
</authorization>
</system.web>
</location>
Upon successful login, I hook LoginUser_LoggedIn to write a destination URL. The problem I am having is the user's roles are not populated upon login, so I'm not getting a good redirect. In the code below, rolesArray has a zero size.
Any ideas? Should I be approaching this from a different angle?
Private Sub LoginUser_LoggedIn(sender As Object, e As System.EventArgs) Handles LoginUser.LoggedIn
Try
Dim rolesArray() As String
rolesArray = Roles.GetRolesForUser()
Debug.Assert(rolesArray.Length > 0)
If (Roles.IsUserInRole("Administrators") = True) Then
LoginUser.DestinationPageUrl = "~/Administrators/Dashboard.aspx"
ElseIf (Roles.IsUserInRole("Engineers") = True) Then
LoginUser.DestinationPageUrl = "~/Engineers/Workspace.aspx"
ElseIf (Roles.IsUserInRole("Customers") = True) Then
LoginUser.DestinationPageUrl = "~/Customers/Dashboard.aspx"
Else
Debug.Assert(False)
End If
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
The same request upon logging in, the cookie is not available for use (for instance, if you check this.User.Identity.IsAuthenticated, it returns false too). It's because the cookie is established during that request, and will be available upon subsequent requests.
I'd recommend redirecting to a common page, then doing this check and redirect again, or query the roles directly from the database using the user Id of the login control.
I need help in following:)
To begin with I work on the large application, that has a WinForms client and server. Server in our case is the set of WCF services. There is one service that is responsible for authentication of users. The logic of authentication is custom and complex and authentication service uses different membership providers.
We want to protect the access to server services for non-authenticated users. The users must firstly authenticate and than use other services (users in this case are the other systems, services, WinForms client, etc.). On this basis, we decided to use the ASP.NET Url/File Authorization feature.
So, I set on the ASP.NET compatibility mode, allowed cookie in all binding configurations, added AspNetCompatibilityRequirements attribute to our services and added the followingconfigurations to config:
<authentication mode="Forms">
<forms cookieless="UseCookies">
<credentials passwordFormat="Clear" />
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
...
<location path="AuthenticationService.svc">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In the authenticate method of our authentication service I add the following code:
public AuthenticationResult AuthenticateUser(string username, string password)
{
AuthenticationResult result = new AuthenticationResult();
result = Authenticate(username, password);
if (result.IsAuthenticated)
FormsAuthentication.SetAuthCookie(username, true);
return result;
}
Next, I wrote the following code:
var authClient = new AuthenticationServiceClient();
var result = authClient.AuthenticateUser("user", "password");
var otherClient = new OtherServiceClient();
var temp = otherClient.DoSomething();
But after authentication I can't access to OtherServiceClient...
So, how can I share the call context between the WCF services calls? Could anybody provide some useful articles about this question?
Thanks in advance!
Best regards.
You need to:
1) Enable sessions in WCF
2) Authenticate using WCF
3) Keep reusing your proxies instead of creating new ones.
This is useful:
http://msdn.microsoft.com/en-us/library/ms733040.aspx
I want to protect a section of my website using forms authentication with the username and password as defined by me in the web.config. When I attempt to login I get the message below.
Server Error in '/' Application.
Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.
I'm guessing this is happening because it's attempting to use the Membership tables as defined by the LocalSqlServer connection string. I don't want to use the Membership features, how do I configure my web app to do that?
Will I need to write the Authenticate function myself for the in-built Login control?
The problem isn't with your config file, it's with the Login control.
The Login control uses the default Membership Provider that is defined in the machine.config. (It's a SqlMembershipProvider that points to a SQL Express database).
You don't want to use the default Membership Provider at all. Simply create your own login page and use the following server-side logic to validate the credentials and log the user into the site:
if( Page.IsValid )
if (FormsAuthentication.Authenticate(txtName.Text,txtPassword.Text))
FormsAuthentication.RedirectFromLoginPage(txtName.Text, false);
else
lblMsg1.Text = "Wrong name or password. Please try again.";
Try this:
<authentication mode="Forms">
<forms loginUrl="Login.aspx">
<credentials>
<user name="Joe" password="Smith" />
</credentials>
</forms>
</authentication>
I am trying to configure authentication using a few tutorials I have found on the Membership Providers paradigm found in ASP.NET v2.0. I've followed the examples in the tutorial but can't seem to get the FormsAuthentication.RedirectFromPage method to work appropriately. When I attempt a login, the user credentials are validated via Membership.ValidateUser but the page is sent back to Login.aspx instead of Default.aspx. Here is the relevant snippet from my web.config:
...
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="60" name="POTOKCookie" requireSSL="false" path="/FormsAuth"
slidingExpiration="true" cookieless="UseCookies" enableCrossAppRedirects="false" defaultUrl="~/Default.aspx"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
...
<membership defaultProvider="CustomizedProvider">
<providers>
<clear />
<add name="CustomizedProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LoginDB2"
applicationName="POTOK"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0" />
</providers>
</membership>
I've verified that my connection string is correct (since Membership.ValidateUser seems to be working just fine) and am using the ASP.NET Login control for the UI on my Login.aspx page. Here is the authenticate event handler code:
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
If (Membership.ValidateUser(Login1.UserName, Login1.Password)) Then
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
End If
End Sub
When I visit the url (http://localhost/Project) I am taken to: http://localhost/Project/Login.aspx and after the "login" my url is: http://localhost/Project/Login.aspx?ReturnUrl=%2fProject%2fDefault.aspx
Did I miss a configuration step?
The problem is in path="/FormsAuth" parameter.
Remove this variable and try again
Read this post about why path can be wrong
From MSDN:
path - Optional attribute. Specifies the path for cookies that are issued by the application. The default is a slash (/), because most browsers are case-sensitive and will not send cookies back, if there is a path case mismatch.
NOTE: The path attribute is case sensitive. Therefore, if the you set the value of the path attribute to /application1, and if the application name is Application1, the authentication cookie path is /application1.
So if you want to use path property, you should set it to "/project" because Project is the name of your application (as far as I understood). But I don't think you need to have different paths when you use different cookies names (i.e. name="POTOKCookie" in this application, i hope will be different from other ASP.NET applications installed on the same host)
See PRB: Forms Authentication Requests Are Not Directed to loginUrl Page
If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.
So, I suggest you simply delete Login1_Authenticate event as far as it does the double work, I think, because control itself is responsible for calling ValidateUser and redirection.
Also check DestinationPageUrl property of the Login control
If you do not specify a value for the DestinationPageUrl property, the user will be redirected to the original page the user requested after successfully logging in. So in your case this property should not be set.