How to Extend Membership in Asp.net? - c#

I am wondering how do I extend the membership stuff in asp.net?
When a user logs in I want to check the UserName and Password. Of course the standard asp.net membership does this(this it is ValidateUser()).
I also want to check another field called "institution". If a user types something in this box I want to verify if the "institution", "userName" and "password" match what is in the database.
If a user leaves the "institution" blank then I just want to use it default ValidateUser() method that is provided in asp.net and check only "userName" and "password".
So can I overload the ValdiateUser() method? Or will I have to write my own one to handle this new case?
Where would I store this "institution" field in the database? I heard something about people recommending the "Profile" table but I am not sure.
Also how can I change the membership to treat these as 3 different users
Institution: ABC
UserName: A09410515
Password: 1234567
Institution: GHA
UserName: A09410515
Password: 1234567
UserName: A09410515
Password: 1234567
So as my database should be concerned these should be 3 unique users. Of course in the case that my database already would have the same information stored in it.
For example.
Institution: ABC
UserName: A09410515
Password: 1234567
and someone tries to sign up with the exact same information for "UserName" and "Institution" then it would spit back an error about being duplicate names.

Yes, you can create a custom membership provider. Your provider will implement MembershipProvider giving you full control over creating an interface between the membership system and extended database schema. Writing A Custom Membership Provider for your ASP.NET 2.0 Web Site is a detailed example.

The lazy way of doing this would be to combine institution and username together to create the actual username.
Thus you'd have 3 distinct usernames: ABC&A09410515, GHA&A09410515, and &A09410515. Just don't allow a user to use & in a username.
Then, before creating the user or logging in you just combine the two strings together.
I can't think of any significant problems that can't be fixed with a simple hack (e.g. displaying the username (use username.split('&')[1] ), but JP's post is definitely the "right" way to do it.
James

You might use Application Name as the institution, that way you would have the same user name in different applications
Rodrigo.

Related

Is it ok to expose messages from the `IdentityError` class?

I'm quite new to the asp.net core identity framework. Many tutorials, articles and guides seem to handle an IdentityError in the same way. They expose the description of the error to the user, i.e. they add the description of the error to the ModelState.
It's been drummed into my head that exposing errors to the user is a terrible idea as it empowers attackers.
So I thought, It must depend on what kind of information is available in the description. For example, if the error is "Your password is too weak" or "You need to enter in a valid e-mail address". That type of information is valuable to the user and should be ok to display. However a "The data source took too long to respond" is already too much information and offers little value. I'd rather catch that type of error and replace it with some generic 500 error.
So my question: Is it safe to show the raw Identity Error to the user? If not how can I filter what I should and Should not show to the user?
I tried looking at the MSDN docs to understand all the possible codes that I could receive. But those docs offer very little information.
I am specifically working with
var userCreationResult = await userManager.CreateAsync(newUser, password);
But it applies to any instance when an IdentityError might appear.
Many software quality and security regulations have audit requirements for this (no error message presented to end users may contain information that is secret or would enable users with malicious intent to compromise the system or access sensitive data), so this is an important question. If there is a documentation or article specifically addressing this, then it is well hidden.
The possible values that the two members of the IdentityError class can assume, are baked into the framework. So it looks like you can be sure that it will always be one of those, unless you obtain an instance of IdentityError from anything else than a UserManager.
The Code field is assigned from nameof of the error method, and the associated Description text is read from core framework resources, so those will be localized.
Source Code
en-us Descriptions
List of errors in current implementation (version 3.0.0):
DefaultError
ConcurrencyFailure
PasswordMismatch
InvalidToken
RecoveryCodeRedemptionFailed
LoginAlreadyAssociated
InvalidUserName
InvalidEmail
DuplicateUserName
DuplicateEmail
InvalidRoleName
DuplicateRoleName
UserAlreadyHasPassword
UserLockoutNotEnabled
UserAlreadyInRole
UserNotInRole
PasswordTooShort
PasswordRequiresUniqueChars
PasswordRequiresNonAlphanumeric
PasswordRequiresNonAlphanumeric
PasswordRequiresLower
PasswordRequiresUpper
Most of these are static strings and do not disclose any variable information.
The following do disclose variable information. This is data previously supplied by the user anyway in the first eight cases, and the value of a server configuration property in the last two cases, minimum required password length and minimum number of unique characters required in a valid password:
InvalidUserName: the user name
InvalidEmail: the email address
DuplicateUserName: the user name
DuplicateEmail: the email address
InvalidRoleName: the name of the role
DuplicateRoleName: the name of the role
UserAlreadyInRole: the name of the role
UserNotInRole: the name of the role
PasswordTooShort: the minimum password length
PasswordRequiresUniqueChars: the number of unique chars required
If that qualifies as "safe" within the constraints and specifications of your project, then the answer is yes.
Regarding your second question on how to do, you could do the following to filter out
a duplicate username as you loop through errors
if (error.Code == _userManager.ErrorDescriber.DuplicateUserName(user.UserName).Code)
{
//Hide info to user by, e.g. redirecting to a page for a registration flow, or display an invalid login attempt for a login flow
}

Assign user based on another table in asp.net mvc4

I'm not even sure how to search for this question, so forgive me if I'm asking a duplicate question and would be grateful for any redirection needed.
I have data (Account Number, Password, Internal Y/N) that is being submitted to an Account Table from Navision. I want to use this data to automatically create a user in the UserProfile table (Username = Account Number, Password = Password) and assign that user to the Admin role if Internal = Y and DealerAdmin if Internal = N.
The data will continue to be maintained for Account numbers in Navision, but the DealerAdmin can add additional users from the website. Is this possible? If so, please provide any pointers to tutorials as to where to start? I presume it's a simple SQL statement. Where do I add this code in MVC so that it gets updated every time there's new data in the Account Table?
If you are using SQL why not use a trigger to create a new record in your User UserProfile when your conditions are met?
If this does not work for you can take a look at the post below and call your proc to move the data over if needed.
ASP.NET MVC 4 intercept all incoming requests

RavenDB Querying to check Username and Password

I'm fairly new to C# and RavenDB, so please excuse my lack of understanding.
I currently have a Windows Form Application. In one of the forms, I have two text boxes and one button. These two text boxes serve as the username and password inputs and the button is obviously there so that the user can login. When the user clicks on the button, a method is called and saves the content of the two inputs in two string variables.
At the moment, in my RavenDB Database, I have created two samples of username and password.
How do I appropriately check whether the username and password given from the user exists in the database.
Any help is really appreciated.
There are two ways to answer this question.
a) You can query for multiple properties using the Linq provider
session.Query<User>().Where(user=> user.Name = username && user.Password = pass).ToList();
b) The problem with this is that this assumes that you are storing the password as plain text in the database, which you should never do.
You can see how we implemented that in RaccoonBlog's RavenDB's sample application:
https://github.com/ayende/RaccoonBlog/blob/master/src/RaccoonBlog.Web/Models/User.cs
https://github.com/ayende/RaccoonBlog/blob/master/RaccoonBlog.Web/Areas/Admin/Controllers/LoginController.cs
As a matter of good security practice you don't store passwords at all, rather you you store the password's hash.
To store your password
Read the values on the server and generate a hashcode of the password. You should use crypto functions to generate hash (such as via SHA256)
Store a document in Raven DB of type User with his username and hashed password
To check if the user with the passed credentials is in the database
Query Raven DB and look for the user with the given name and password hash.
Sample code
var user = session.Query<User>()
.Where(u => u.UserName == "Alice" && u.HashedPassword == "hashPwd");

I don't understand how email activation works

I want to verify that the user email is valid and turn this email into his id in my system.
Yet I don't know how to make a link in the mail, that activates the account like(facebook and others
) and I don't really understand what happens when the link is selected.
I thought of generating a key like "sdklbsdgk4493" to enter once- so that guessing is hard, yet for many people copy and paste is not trivial and I may annoy them with this solution.
Any thoughts or ideas?
p.s: I'm working in c# so if it can be done with c#... it will be great :)
Thanks Asaf
When you insert a new user in the Database, their status should be "Deactivated" and you insert a "GUID" you generate alongside. You send them a link to your activation Page which would contain this GUID in the Query String. It will look like this:
www.YourSite.com/Activation.aspx?GUID=jdfhg43h98234
In the Activation.aspx page, you take this GUID from the Query String and compare it to the one you have in the Database. You then activate the Account having that GUID.
Create the user
Generate a unique string for the user
Have a Table that stores the unique string, the user Id ,a boolean that holds whether it got activated or not, the generation date, the expiration date and if you have different uses for these activation strings, the type(link to another table)
Now within the email you should get the string and write it within the email along with a link to the page you're going to use for validation such as whatever.com/verify.aspx?activationString=hd3fd33fen342n43
Within this page you do a query search within the table that holds the keys and if its not already validated
You have your users table in the DB (or where ever it is that you store your list of users), just add a column stating if the user's mail is validated.
To the validation mail add a link that fires some PHP with a user-specific code (like it's index in the DB). The PHP will set the user's "validated" column to true, and it'll be done.
It's not as complicated as it may seem at first.
The idea is to create a random key, save it to the database connected to the useraccount, supplying a link to the users e-mail which could point to a webservice(or regular website) which takes the key as a querystring which will then activate the account connected to that specific key.

How to deal with arrays of data in cookies

I want to store data in a cookie and I am not exactly sure how I will go about it.
The data is the UserName, and Password values for the users that are logging into a website, e.g. sometime like this
UserName = bob, Password=Passw0rd1
UserName = harry, Password=BLANK
UserName = george, Password=R0jjd6s
What this means is that bob and george logged into the site and chose to have their password remembered, but harry chose for his password not to be remembered.
So on the login dialog a dropdown will be present with all the usernames in it 'bob', 'harry', 'george'. If they select the username bob the password will automatically be filled in, etc.
So how does that information need to be stored in the cookie? Like it is above, or does it have to be,
UserName1 = bob, Password1=Passw0rd1
UserName2 = harry, Password2=BLANK
UserName3 = george, Password3=R0jjd6s
Are the username and password values actually stored in the same cookie, or is each piece of data separate? Any information would be good.
As far as whether or not all information should be stored in a single cookie or multiple cookies depends on how many cookies you plan on creating and whether or not you want all the information to expire at the same time. Generally, for efficiency, you will group related data into a single cookie.
However, it is a bad practice to store passwords in a cookie, since this information would then be plain-text and easily readable by an attacker.
The following link provides some guidance on cookies and asp.net.
http://msdn.microsoft.com/en-us/library/ms178194.aspx

Categories

Resources