Web Forms :: Membership Authentication In Session_start?
Jan 13, 2011
I've written an asp.net 3.5 app using a custom Membership provider. Normal auth is working great. I have an older site (asp.net 1.1) and I want to connect the two through a database drive time sensitive security key that is passed from one app to another. By using that I can find the user in the db.
I want to use this information to auto-authenticate the user and fill session objects in the new app. I've looked at the session_start in the global.asax file, and have tried FormsAuthentication.SetAuthCookie(), but he still shows up as unauthenticated.
I have setup a trivial preview website for a client that needs basic password protection. I'm using Forms Authentication with the credentials specified in web.config.
Everything works fine on my box (famous last words)
However, when I deploy to a production website running Win2008, the authentication code attempts to open a SQL Server database (I have no reference to anything SQL in web.config). How can I disable this behavior so that authentication is based on the credentials I have entered in web.config?
Exception in Event Log
Unable to connect to SQL Server database. at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) at System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString) ... at System.Data.SqlClient.SqlConnection.Open() at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)(URL)
Unfortunately, all the examples for Forms Authentication Code Behind w/ Custom Role and Membership Providers I find online are written with a VB.NET code behind and I need a C# code behind. I need a codebehind that will do the following:
authenticate user upon login button click if user active_flag=0 (false) OR password!=@password, display error: "Access Denied" if user admin_flag=1 & active flag=1 (true), redirect to admin_pageszipsearch.aspx if user admin_flag=0 (false) & active_flag=1 (true), redirect to pageszipsearch.aspx
I have implemented the .Net Membership provider with my website which is, for the most part, working well. However, occasionally a user will try and login and nothing will happen. There will be no error, they will just hit "Submit" from the login screen and continue to the homepage as an unauthenticated user. This behavior persists until they clear their web cache, or restart their machine... which makes me think it's some kind of cookie expiration error?
Does anyone have any ideas on how to troubleshoot this?
I am developing an MVC2 application an am using the built in Membership provider. I am just asking myself if the authentication is on the server or the client?
I need to convert a web site using traditional ASP.Net login,membership/role with SQL to a custom system. I need to use a third party (CAS) authentication system while still using membership and roles to control access to content and User.Identity functions.What would be the best way to accomplish this? I use the <deny> and <allow> user throughout the site to control page access.
I have a SqlMembershipProvider store with Roles enabled. This is configured and has the user "devtest" in the roles "xxUser" and "xxAdmin".
I also have a WCF service, which I want to authenticate and authorize against. My problem is that:
the authorisation is not happening, code just executes despite the policy attribute I don't get any identity or security context so do not know who is calling the service I need: to know which user is calling the method some degree of rejecting users if permissions don't match (ideally this should be performed within the RoleProvider/MembershipProvider/WCF but can do it myself if I have to) SSL in transport
I have my service contract set up thus:
[ServiceContract] public interface ISupportService { [OperationContract] [PrincipalPermission(SecurityAction.Demand, Role = "ThisRoleDoesNotExist")] List<BaseInterestRate> GetAllBaseInterestRates(); } the code is simple enough: public class SupportService : ISupportService { public List<BaseInterestRate> GetAllBaseInterestRates() { OperationContext operationContext = OperationContext.Current; ServiceSecurityContext serviceSecurityContext = ServiceSecurityContext.Current; // is always null using (xxxEntities entities = new xxxEntities()) { return new List<BaseInterestRate>(entities.BaseInterestRates); } }} My service configuration is thus: --> <behaviors> <serviceBehaviors> <behavior name="SupportServiceBehavior"> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="AspNetSqlRoleProvider" /> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="SqlMembershipProvider" /> </serviceCredentials> </behavior> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
I have followed the instructions at these pages to the letter:
How to: Use the SQL Server Role Provider with Windows Authentication in WCF Calling from Windows Forms (MSDN) How to: Create and Install Temporary Client Certificates in WCF During Development (MSDN) How to: Use wsHttpBinding with Username Authentication and TransportWithMessageCredentials in WCF Calling from Windows Forms (MSDN) Also quite useful found via SO: Use Asp.Net Membership provider with a WCF .svc service (Alkampfer's Place)
I would at lest expect an issue with certificates/transport/etc. to fail with exceptions, but I can debug right in and over the WCF call. I have no security context/ user context available to me and when I use a user not in the two mentioned roles (which I do in the code example above), I don't get "kicked out".
My client app is currently a Web App, but will ultimately also serve a Windows Forms app and Test suite. I'm currently using the ASP.NET WebDev server and am running .NET 4.0.
I have an old website running fine in Classic ASP with large customer base registered onto the site. The current site allows users to have their own user name(unique) registered against an ID assigned to them. They can change the User name later as well provided it is still Unique in the database(Database is SQLServer2005).
The Problem: Now i want to move the website to .NET and want to use the .NET Membership. I know how to create the database structure in SQL Server through aspnet_regsql script but my problem is how should i import the existing username and passwords as the password stored in MembershipDB is Hashed (salt). Also i might want to allow admins to impersonate as users later.
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:
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?
Without reading the whole text below, since this is on the ASP.Net side ... basically I think I need to know if there is a way to reduce the size of the forms authentication cookie. When using a DotNet 2.0 website, the ASPXAUTH cookie is about 232 bytes ... when using the same source code but upgraded to DotNet 4.0. the cookie is approximately 264 bytes, setting the ticketCompatabilityMode does not reduce the size since I think the default setting is Framework20. I length of the cookie, including the its' name can not be larger than 256 bytes in order to use it with the "Client Application Services".
I only did a cursory search of the asp.net forums, but will dilligently look for an existing solution.
----- BACKGROUND AND RESEARCH -----
I have been using all three features of client application services (authentication, profiles, and roles) in my windows app (DotNet 3.5 framework) for almost two years now. Up until now, I have not had any problems. This week I hit a brick wall and am pretty stumped with two seperate but related issues.
Issues:
In development, we decided to upgrade our websites/services to DotNet 4.0. All applications upgraded successfully. However we are unable to log into our application using Client Application services. No matter what user we use, Membership.ValidateUser returns false. Since we know the username and passwords, we thought this was strange. When debugging the application, we found that Membership.ValidateUser was throwing an InvalidOperationException (see below for complete exception) stating that the ASPXAUTH property was too long, longer that the schema created in the SQL/CE database. (See below for things tried).
In production .. A user all of the sudden could no longer gain access to the application. Upon inspection, his ASPXAUTH cookie was 264 characters long (9 characters longer than the schemas nvarchar(256)). Even though the user was being authenticated on the "server side", and the JSON query returned "{"d":true}", Membership.ValidateUser returned false. Again, as in the case above, the actual error was ...
I am assuming I am missing something very simple or that I overlooked a settings. In development, this is not a huge issue as I can release the Dotnet 4.0 websites when I am ready. But now that this has happened to a client on a production system, it is very worrisome.
I am evaluating ASP.NET Membership for an intranet Silverlight app. I want users to be automatically authenticated for my application with their windows logon. Thus I configured Windows Authentication. I would like to store user settings like email-address in using the SqlMembershipProvider and not AD. It seems that storing user settings using the SqlMembershipProvider is not supported with Windows Authentication. Is this really so (using .NET 4)?
If so: What is the rationale behind this? IMHO authentication, user settings and authorization are distinct aspects. User settings could easily be stored (identified by user name) using the SqlMembershipProvider with authentication and password management being supplied by Windows. What is the recommended solution for my scenario?
1. user can login by their AD account and password.
2. AD account can be assigned to different group.
I know there is a training video - [URL] to teach how to use the tool to provision the membership schema to SQL server for Forms authentication. but how can I use AD authentication with this?
I just like to know how can i create my own authentication(calling the ASP .net membership, role) page with the same function as the LOGIN Control. Your wondering, why not use the Login control instead. I have my own design and i don't know how to pattern my design to the built in Login Control. I tried editing the login template, but it's pretty hard to pattern it to my design.
This is my design
Basically what would like to know how the Login Control calls for the authentication, and when authenticated, it will pass the user(full name) to my LoginView Control without any coding. Or is it possible that I remove default login button in the LOGIN Control then create my own button and trigger the authentication or validation? But if you have other suggestion that can follow my design and call the authentication, i would be happy to know.
my user will use form authentication against Active Directory or database. Theres no Windows Integrated Authentication there!!
What i want is when the user submit the authentication form, it will try to validate the user against Active Directory and if it fail, try with the database.
How can i do that? What i had in mind was to build a custom membership provider that will encapsulate the logic but im not sure how to start.
I've been asked to upgrade a few applications and I'm planning on merging all of them into one asp.net application. I'm fine with this decision and have spoken with fellow workers and they also think it's the best option to go with.
The application will be accessed from a small group of users which belong to a larger domain. I'm currently planning on using Windows authentication and only allow this small set of users to access the asp.net application. Also there must be some role management, so that only certain users can view certain functionality.
I really don't want to have many different windows groups; so I want to avoid having to assign different windows groups to different folders and control permissions in the web.config.
What I'd like to do is:
- Assign one windows group to the small group of users who will access the page.
- Create a custom membership provider and control the user who accesses the application. Depending on the user I will then assign his current set of roles.
- Add an application setting to the web.config, with the name of the current administrator, so if he logs in, he will be assigned all roles, and will be able to create and assign roles to other users.
I'm developing a web application using EF4, POCO's, WCF Data Services and the presentation tier (HTML, CSS, JavaScript, Ajax - NO WebForms). For security I would like using ASP.NET Membership Provider (Authentication Service): from a *.htm file calling the AuthenticationService. I executed aspnet_regsql.exe (to create the necessary database tables) and modified my web.config file:
I am having an issue, with the membership and form authentication. I am having a problem where when an logged in user types a url they can see the content of pages they're not suppose to. When the user tries to click on the screen or any ajax fires they are redirected to the main page. What is going on? I have all the items setup in the webconfig properly just wondering what is happening. Also I don't want to use a redirect solution for each page since that is what I thought webconfig was setup for.
I'm running a 2.0 .NET app on my local machine; the app uses Global.asax to trigger logic at both Application and Session Start. Up until this week, session management in this application was behaving normally. Now, after no apparent change to my system, it is not. The application has a sign-on screen at startup, in which the user selects a user profile, and proceeds to a main menu. The user info is stored in a Session object, and carried forward to the main menu for the remainder of the application. Normally, a new session is created when the user times out; however, I am finding now that, on my machine, a new session is created on each form change (Response.Redirect, window.open, etc.)
Web.config for the app, when testing locally, uses a <sessionState> setup of 'mode="InProc" cookieless="false"'. My IE7 browser is set up to "Always allow session cookies". When I attempt to run the app 'cookieless="true"', it works up to a point where a popup form is displayed, at which point a new session is created, and the Session_Start logic kicks in, where I lose my user info characteristics. This in turn triggers logic which assumes the user timed out, and a "Session Expired" screen is presented.
I do not have IIS installed locally; ASP.NET is used for session management. I have tried setting the timeout to an extremely high value, without effect.
I'm running a ASP.NET website on my development box (.NET 2.0 on Vista/IIS7).
The Session_Start method in global.asax.cs logs every call to a file (log4net).
The Session_End method also logs every call.
I'm using InProc session state, and set the session timeout to 5 mins (to avoid waiting for 20 mins).
I hit the website, wait for 5 minutes unit I see the Session_End logging. Then I F5 the website. The browsers still has the session cookie and sends it to the server. Session_Start is called and a new session is created using the same session id (btw: I need this to be the same session id, because it is used to store data in database).
Result:
Every time I hit F5 on a previously ended session, the Session_Start method is called.
When I open a different browser, the Session_Start method is called just once. Then after 5 minutes the Session_End each F5 causes the Session_Start method to execute.
Update:
After the Session timeout, all subsequent requests have a session start & session end. So in the end my question is: why are the sessions on these subsequent request closed immediatly?
I'm using BlogEngine and i'm changing it a little bit. I tried to show the online visitors number. I added some code in global.asax. My approach is like:
I defined the count of visitors in App start like Application["OnlineVisitors"] = 0
then i increased the count with 1 in the session start and decreased it in session end but it's not working. I downloaded the website to debug in my computer but i never comes to the breakpoint in the session start function. Also sessionstate mode is inprog cookieless= false and timeout = 20
how to implement the authentication and membership for a hobby project I'm working on. Tought I'd ask for opinions here. I started using the asp.net membership/authentication/profile providers. First off I want user's to "activate" their accounts, so upon registration I figured I'll set "IsApproved" to false, generate and email an activation code which I store in a user profile. User's won't have usernames, just log in by email address. While it's easy to pass an email address as username, I'm worried about user's having to change their email addresses (used for logging in) later.
I am writing two ASP.NET apps. One is a web service that provides xml data and the other is a web client that will use the service to display and manipulate data. I would like for the web service to do the membership authentication and authorization. Is there any way to simply point the login controls in my client application to the web service instead of to a database. I assume I would have to provide the necesarry methods in my web service interface, which would then use the membership provider database I created and pass the results back through to the client.
Is this possible? I have seen many articles on security provisioin from a web service but none has really been what I am looking for. I was hoping that, since my service and my client are both written in ASP.NET, there might be some built functionality that would benefit me.
I have a custom provider for authenticaiton that is HTTP Module-based. IIS authentication and web.config authentication is configure to 'None' and allow anonymous. When I probe for User.Identity.Name in Session_Start, it is empty. However User.Identity.Name works elswhere in the application as expected (returns the current user id). Is it possibly during Session_Start no authentication request has been issued, therefore there is no principal at this moment?