I have my own database (SQL Server 2008 RQ) and i have a table name "Users"
I wanna use ASP.NET MemberShip with my table (Users) how can i do this ?
I don't want to use normal DataBase, i wanna change tables and fields because i want to personalize it.
I don't want to use Profile, i want to change tables and fields, i know i can create my own authentication system but i want to use Login Control from ToolBox and other Controls.
Please give me suggestions.
This is fairly easy. You just have to create your own class inheriting from MembershipProvider and register it as a default provider. One of its methods in particular is designed to validate users' credentials. The builtin Login will use your own code, as long as you register your provider.
public class MyCustomMembershipProvider : MembershipProvider {
// a lot of methods required by the abstract class
public bool ValidateUser( string UserName, string Password ) {
// use your own database to validate user credentials
}
}
and then
<system.web>
<membership defaultProvider="MyCustomMembershipProvider">
<providers>
<add name="MyCustomMembershipProvider" type="MyCustomMembershipProvider" />
</providers>
</membership>
In case of any doubts, follow the example:
http://msdn.microsoft.com/en-us/library/44w5aswa.aspx
You can implement a custom MembershipProvider to use your own database schema.
Create your own custom membership provider; see this:
http://msdn.microsoft.com/en-us/library/aa479048.aspx
http://www.codeproject.com/Articles/165159/Custom-Membership-Providers
HTH.
Related
I have an Asp.Net MVC 5 application. I want to use user roles to authorize only some people to use a specific action. I've changed my Web.config file like this:
<roleManager enabled="true"/>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
This is how I add users to roles:
if (!await Roles.RoleExists(role))
await Roles.CreateRole(new Role(role));
await Roles.AddUserToRole(role, user.Id);
Currently I am able to access the roles for a user through code using something like this:
public static async Task<IEnumerable<string>> GetUserRoles(string username)
{
if (string.IsNullOrEmpty(username))
return new string[0];
string userId = await Logins.GetUserId(IdentityConfig.LocalLoginProvider, username);
var roles = await Roles.GetRolesForUser(userId);
return roles;
}
However, when I try to use the Authorize attribute to access the roles, the page will get stuck and nothing loads.
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
return View(db.Restaurants.ToList());
}
What am I doing wrong here?
Update:
After a while the webpage will show this error:
You cannot really mix the old membership/roles with the new identity system. You need to pick one or the other. The authorize attribute should work fine assuming you added the user to the admin role via the new identity apis.
At the bottom, this article demonstrates roles Mvc5 tutorial
I had the same problem, it has nothing to do with your connection string. Add the following to your web.config:
Here's the answer: http://blog.luppes.com/2013/12/08/mvc5-authentication-roles-failure/
As of ASP.NET 4.5.1/VS2013, MVC as of MVC5 is no longer a separate product, but is now completely integrated into ASP.NET. This is part of Microsoft's new One ASP.NET strategy.
In addition to this, Microsoft has developed a new kind of identity management system called the ASP.NET Identity, which does not use the legacy membership system.
Basically, if you want to use the old membership system, you need to use MVC4 or earlier. If you want to use ASP.NET Identity, then MVC5.
I am relatively new to authorization/memberships in asp.net, so pls excuse if I ask anything silly. I have been looking at lot of examples to implement a custom membership provider in .net (in stackoverflow, codeproject, devX, and www.asp.net) and coded based on that but somehow couldn't get it working.
My requirement - our organization heavily uses HP's Quality center(QC), I am developing an asp.net application, its login page will use QC'a API for authenticating a user. I also have a SQL database in which I'll store the QC users who have registered to my application (just store QC user id's in DB, not password, like I said, password authentication is done using QC API). There will be a user-roles table in my DB to define the roles for registered users.
Why use 'membership' instead of some simple 'forms authentication' - because maybe in future I want to decouple QC authentication.
So, with this I started with first step - developing custom membership class(named AutoCenterMembershipProvider) and login page. I only need validateuser method. following is the approach I took to start with:
1. Ask user for QC user id/password, user clicks 'Authenticate' button
2. login page's code behind-'Authenticate' button's onClick method- checks if user is found in SQL database and if found, then uses QC API to authenticate user id-password
3. Second set of controls on Login page is enabled - ask user to select which QC Domain and Project user wants to login. Options for Domain and Project dropdown lists are also obtained using QC API after authenticating user. User selects those and clicks Login button
4. On Login button's click - call Membership.ValidateUser(objQCSession.UserName, objQCSession.Password). Since user is already validated using QC api, for simplicity I just return 'true' from my custom implementation of Membership.ValidateUser. Then I call - FormsAuthentication.RedirectFromLoginPage(obj_ACUser.QCSession.UserName, True) to direct user to apps default page provieded in web.config's - app_FAs.aspx.
The issue is - after user is redirected to app_FAs.aspx page, it directs user back to login page. I am trying to find out the mistake or missing piece.
Web.config looks like below:
<authentication mode="Forms">
<forms loginUrl="~\Pages\Login.aspx" defaultUrl="App_FAs.aspx"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<membership defaultProvider="AutoCenterMembershipProvider">
<providers>
<clear/>
<add name="AutoCenterMembershipProvider"
type="CustomMembership.Models.AutoCenterMembershipProvider"
enablePasswordRetrieval="false" enablePasswordReset="false"
requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="100" minRequiredPasswordLength="100"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="100" applicationName="/" />
</providers>
</membership>
and customMembership class is like:
Public Class AutoCenterMembershipProvider
Inherits System.Web.Security.MembershipProvider
Public Overrides Function ValidateUser(ByVal username As String, ByVal password As String) As Boolean
Return True
End Function
rest all members are 'Not implemented'
any help, pointers to missing piece, mistake is greatly appreciated, thanks in advance
Authenticate button click code
Private Sub btn_Authenticate_Click(ByVal sender as Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_Authenticate.click
objQCSession = Session("QCUserSession")
If Membership.ValidateUser(objQCSession.UserName, objQCSession.Password) then
FormaAuthentication.RedirectFromLoginPage(objQCSession.UserName, True)
End if
End Sub
Currenlty, 2nd step - btn_Authenticate_Click method 1 - is just to assign FormAuthenticationTicket to cookie, and redirecting user to app_FAs.aspx page. It doesn't really need Custom Membership Provider's features.
If I understand your problem correctly, I would change the logic like this.
1) After validating user for QC, create FormAuthenticationTicket like this in the same method.
FormsAuthentication.SetAuthCookie("UserName", true|false);
2) btn_Authenticate_Click (does something and) redirects user to app_FAs.aspx
You do not even need Custom Membership Provider. If you want to use Custom Membership Provider, you can implement in 1st step (Not in 2nd step).
I am creating an ASP.NET MVC 4 web application. I googled about custom membership, but I couldn't find good resources or video lectures.
Most of them are either outdated or dead links. Please could you suggest some resources about how to start writing a membership and role provider.
Understanding about membership and roles was pretty difficult for me too, as you said there are not many reliable and detailed content you will find on web. I tried watching several videos to Understand about this topic but wasn't clear. But then two articles from a website called Code Project came for the rescue. I am sharing these Link where you can see a step by step guide about customize membership
Link 1
The link 1 will help you to replace an email with username for login authentication this is one of the most common customization the developers need in the microsoft provided Identity Module.
Link2
The second article will help you understand adding and attaching roles to the created user and how to limit the access of user registration page to an Admin only. This way with the help of these two articles I hope that you will Understand the Basics of Authentication and Authorization.
I suggest using ASP.Net Identity instead of old membership.ASP.Net Identity is a way better and more flexible than old membership, it also supports role-based authentication using action filters and you can implement your own customized providers (such as role and user providers).
see links below
https://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application
http://www.c-sharpcorner.com/article/create-identity-in-simple-ways-using-asp-net-mvc-5/
The ASP.NET MVC 4 Internet template adds some new, very useful features which are built on top of SimpleMembership. These changes add some great features, like a much simpler and extensible membership API and support for OAuth. However, the new account management features require SimpleMembership and won't work against existing ASP.NET Membership Providers
Check out resources for ASP.NET Identity here:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-recommended-resources
http://logcorner.com/how-to-configure-custom-membership-and-role-provider-using-asp-net-mvc4/
**for creating a CustomerMemberShipClass** your class must implement System.Web.Security.MembershipProvider abstarct class. and you override the method ValidateUser()
in this ValidateUser() you have to write your own logic based on which you want authenticate user and return true or false according to it.
Sample ValidateUser method
public override bool ValidateUser(string username, string password)
{
int count=db.GetAll().Where(x => x.UserEmail == username && x.password == password).Count();
if (count != 0)
return true;
else
return false;
}
later in web.config file you have add the fallowing under <sytem.web> element
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider" type="Write your class name that is implementing membershipproviderclas"/>
</providers>
</membership>
after doing this you can validate user using **MemberShip.Validate(Username,password)** which returns true or false based on ur code in ValidateUser() in CustomMemberShipProvider class and this will also set **[Authorize] attribute**
**for creating a CustomRoleProviderClass** your class must inherit System.Web.Secuirty.RoleProvider and override the appropriate method to get the roles for the user
SAmple method for getting roles for user
public override string[] GetRolesForUser(string username)
{
string[] str={db.GetAll().Where(x=>x.UserEmail==username).FirstOrDefault().Role};
return str;
}
after this you must add the fallowing in web.config file in <system.web> element
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<clear/>
<add name="MyRoleProvider" type="BLL.DoctorAppointmentRoleProvider"/>
</providers>
</roleManager>
and after this u can check the role of the user using attribute **[Authorize(role="admin"])** and in Razor view you can check using User.IsinROle("A").
I am learning the migrations feature available in Entity Framework and I seem to hit a problem. When using an internet application project template and enabled entity framework migrations etc. I am trying to just create a default user onto the database - using an automatic migration:
protected override void Seed(eManager.Web.Infrastructure.DepartmentDb context)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Email", false);
if (!WebSecurity.UserExists("ahicks2"))
{
WebSecurity.CreateAccount("ahicks2", "password", requireConfirmationToken:true);
}
if (!Roles.RoleExists("Admin"))
{
Roles.CreateRole("Admin");
}
}
When I run "Update-Database -verbose" in the package manager I get the following error:
Running Seed method.
System.Web.Security.MembershipCreateUserException: The Provider encountered an unknown error.
at WebMatrix.WebData.SimpleMembershipProvider.CreateAccount(String
userName, String password, Boolean requireConfirmationToken)
at WebMatrix.WebData.WebSecurity.CreateAccount(String userName, String password, Boolean requireConfirmationToken)
The next line in the stack trace is the Configuration.Seed call. In my web config I am using the following setting for the membership provider to guarantee the tables are created in the database I want:
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<clear/>
<add name="DefaultMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"/>
The database tables are being created correctly, but the code falls over on the create user. Can anyone help? I'm sure its something simple. I wanted to test out these features - of course a simple answer is to revert back to using membership providers from asp.net 2.0! but I wanted to try and get this to work. Any help would be appreciated.
EDIT: By the way I've tried this: http://forums.asp.net/t/1598261.aspx/1 and it doesn't solve this problem.
The answer lies on the surface.
Take a look at the MSDN page regarding this method:
WebSecurity.CreateAccount Method
It presumes that matching user information (represented by userName) already exists in the user profile table. (To create a new user in both the membership table and in the user profile table, use the CreateUserAndAccount(String, String, Object, Boolean) method.)
This worked for me:
WebMatrix.WebData.WebSecurity.CreateUserAndAccount("YOURUSERNAME", "YOURPASSWORD");
You mght also wish to consider making sure the controller/class has
[InitializeSimpleMembership]
I'm trying to do a similar thing as you and struggling!
I'm failing with creating a role.
Dan.
How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project?
Can UserId be included in Profile namespace next to UserName (System.Web.Profile.ProfileBase)?
Try this:
MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
Response.Write("CurrentUser ID :: " + CurrentUser.ProviderUserKey);
Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache.
If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId.
If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider.
EDIT:
See ScottGu's article on providers which provides a link to downloading the actual source code for i.e. SqlMembershipProvider.
But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it.
For something more to consider (but be very careful because of cookie size restrictions): Forms Auth: Membership, Roles and Profile with no Providers and no Session
I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago.
My original question was about UserId and it is not available from:
System.Web.HttpContext.Current.User.Identity.Name
Try the following:
Membership.GetUser().ProviderUserKey
public string GetUserID()
{
MembershipUser _User;
string _UserId = "";
_User = Membership.GetUser();
Guid UserId = (Guid)_User.ProviderUserKey;
return _UserId = UserId.ToString();
}
You have two options here:
1) Use username as the primary key for your user data table
i.e:
select * from [dbo.User] where Username = 'andrew.myhre'
2) Add UserID to the profile.
There are pros and cons to each method. Personally I prefer the first, because it means I don't necessarily need to set up the out-of-the-box profile provider, and I prefer to enforce unique usernames in my systems anyway.
Andrew: I'd be careful of doing a query like what you've shown as by default, there's no index that matches with that so you run the risk of a full table scan. Moreover, if you're using your users database for more than one application, you haven't included the application id.
The closest index is aspnet_Users_Index which requires the ApplicationId and LoweredUserName.
EDIT:
Oops - reread Andrew's post and he's not doing a select * on the aspnet_Users table, but rather, a custom profile/user table using the username as the primary key.
I had this problem, the solution is in the web.config configuration, try configuring web.config with these:
<roleManager
enabled="true"
cacheRolesInCookie="true"
defaultProvider="QuickStartRoleManagerSqlProvider"
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="30"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
createPersistentCookie="false"
cookieProtection="All">
<providers>
<add name="QuickStartRoleManagerSqlProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ASPNETDB"
applicationName="SecurityQuickStart"/>
</providers>
</roleManager>
{
MembershipUser m = Membership.GetUser();
Response.Write("ID: " + m.ProviderUserKey.ToString());
}
Will give you the UserID (uniqueidentifier) for the current user from the aspnet_Membership table - providing the current has successfully logged in. If you try to <%= %> or assign that value before a successful authentication you will get the error "Object reference not set to an instance of an object".
http://www.tek-tips.com/viewthread.cfm?qid=1169200&page=1
Have you tried using System.Web.HttpContext.Current.User.Identity.Name? (Make sure to verify that User and Identity are non-null first.)
internally it's executing below script in sql server
select * from vw_aspnet_MembershipUsers where USERNAME like '%username%'