Create my own authorization and authentication system in ASP.NET MVC - c#

I'm working on an ASP.NET project, and i want to create and use my own authorization and authentication system to manage users (in a sql server database) like login, check authorization, and check authentication, i know in ASP.NET we have Identity but I want to create my own system.
so my question is do anyone have a good algorithm or a structure or just and idea for a custom system ?
Massive thanks in advance.

You can start from simple things, creating a model of User with ordinary fields Login, Password, and AuthController that will have two methods RegisterUser and SignIn.
RegisterUser - here you have to check if Login already exists, if not - insert data to table Users. Important thing - you have to choose algorithm to encrypt user password and save it in DB.
SignIn - method that will also check if user by Login and Password exists in DB (encrypt password from request by your algorithm and check if exists the same in Users table), if he is - you have to create a token and return it in response (to give an access to your portal).
Actually we can attach to it validation to a models (see https://fluentvalidation.net/), restore password logic with email notification and so on. A lot of examples with custom features of authorization and authentication you can find in the internet. Just separate your functionality into parts and google it.

You could fork from Identity Server 4 and create your own implementation. They have a good base to build a solution from and has integration with many app types using OpenID and OAuth. https://identityserver4.readthedocs.io/en/latest/

Related

authentication against ADFS, authorization against sql server

after several days of searching, reading and trial and error i definitely need some help.
The Situation:
I need to create a Web-Application using MVC where users are authenticated against an AD using ADFS. But they do not want to store the Roles and further Informations into the AD. So i need to read and store those informations somewhere else. My first thougt was to use the same infrastructure which VS sets up when i created a new Web-Application and choose "Individual User Accounts".
What i've done so far:
I created a new Projekt in VS and implemented the authentication against the AD using the ADFS (using this really helpful link(http://www.cloudidentity.com/blog/2014/02/12/use-the-on-premises-organizational-authentication-option-adfs-with-asp-net-in-visual-studio-2013/). Works fantastic.
Start eating my Keyboard because i can't get the next step done.
My Question/s:
Is this possible to authenticate users using the ADFS and retrieve further informations (like Roles, other properties (e.g. Department)) about the logged in user by using / extending the ASP.NET Identity Framework? Does someone have a nice link?
I'd be glad for any help.
No need to do the work in your web app...
You can simply have ADFS source the claim info from a SQL database.
Do Add Attribute Store..
Set Attribute store type to SQL
Enter a Display name and your Connection string
Then when adding the claim to the relying party choose a Claim type
of "... Custom Rule" and have the query you enter fetch the attributes from your DB.
There's a pretty good walkthru with more details in TechNet
The problem you have is that you have to map the AD claims to the ASP.NET Identity via some kind of primary key.
Good link here : Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on (C#).
(With ADFS 4.0 (Server 2016) you will be able to use a SQL DB for authentication and authorization).

Authorization with using Windows Account

In my Windows Store App (c#) I have own authorization mechanism:
User past their account name / password and sent it to server.
Server generate unique token and returns it to user.
For all next requests user used this token.
Now I'm in trying to make authorization with using only Windows Account.
MSDN provide UserInformation class and I can get name for the user account or domain name for the user. But I thing this is not enough for my authorization scheme.
Also method GetSessionInitiationProtocolUriAsync looks very interesting, but I don't know how correct use such Uri for authorization.
How I can use Windows Account for authorization in my application?
note: I'm interested in both situation: when user inside domain or not.
Thanks.
There is numerous was to implement this but if you want to keep it simple and own the process you could implement your own authentication method which on a successful authentication you could build a hash value from their password and secret salt which could be returned to the user as a cookie etc. which you use to validate on every request there after.
On regards to authorisation you can implement your own or use a role based provider linked to the local machine group or active directory by using the classes below or just using the plain old RoleProviders.
You could implement your own method of authentication using the method described below or using the Authentication and Authorisation provider for ASP.Net (if your server runs on .net). Basically the Asp.Net Membership and role Providers. However the method detailed below will allow you to access and modify roles and other information about the user too.
In .Net 3.5+ there is a new namespace called System.DirectoryServices.AccountManagement.
Snippet from MSDN
The System.DirectoryServices.AccountManagement namespace provides
uniform access and manipulation of user, computer, and group security
principals across the multiple principal stores: Active Directory
Domain Services (AD DS), Active Directory Lightweight Directory
Services (AD LDS), and Machine SAM (MSAM).
System.DirectoryServices.AccountManagement manages directory objects
independent of the System.DirectoryServices namespace. Managed
directory services applications can take advantage of the
AccountManagement API to simplify management of user, computer and
group principals. Solutions that previously required intricate
knowledge of the store or lengthy code, such as finding all groups to
which a user belongs, are accomplished in a few lines of code with the
AccountManagement API.
You can easily authenticate a user credential on AD using the code below:
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
If you want to validate using a local machine account you can change the constructor too:
new PrincipalContext(ContextType.Machine)
You can check the documentation for other options and additionally this will let you get all sort of information from the store like membership etc.
The new namespace was Microsoft attempt to simplify DirectoryServices which I think was successful but if you want even more control you could use the DirectoryServices classes but that would increase the complexity of the solution.
I hope this helps if you require further information or you think it is not quite what you are looking for let me know I will endeavour to improve the answer.
First, I'm afraid you're confusing authentication and authorization.
Authentication - proving a user's identity (like me presenting an ID when going to the bank)
Authorization - deciding whether an identity is allowed to perform some action (like whether the client "Nitz" can drain account #44422).
A Microsoft account can only provide you with authentication - the client will use some scheme to prove to your server that it belongs to bla#microsoft.com, and it's up to you to decide if it is allowed to do stuff in your application (authorization).
With domain accounts, you can use domain group membership to help with your authorization (it's even common in windows server applications), which you usually get "for free" with the user's authentication token.
Assuming I understood you correctly and you're indeed looking for authentication, you have to provide two behaviors - one for using domain authentication and one for Microsoft account authentication. This is because libraries and communication protocols are very different between the two.
Providing authentication
Using this this tutorial from Microsoft Azure's guys, you can set up a sample application / website combination that utilizes Microsoft account authentication.
To use domain authentication (kerberos / NTLM), you can follow this post and simply enable "integrated windows authentication" in your web site/service (I'm assuming it's IIS). If you're new to enteprise authentication, I'll shortly say that when set up properly (no time differences, AD issues etc.), the authentication is seamless. If there are issues, fall back to a simple "hello world" website and test it from Internet Explorer.
For each scenario, you best create a "hello world" method returning the user's authentication information, to make sure you got it right.
Providing authorization
with each authentication method you end up with a unique ID (Microsoft account: UserId. Domain accounts: SID). Your logic should translate this info to a set of permissions - e.g. Maintaining a table that has the ID in one column, and isAdmin in another. Your application should consult this logic when deciding whether to allow or deny an action from a client.
Combining enterprise and public
Since the methods to authenticate public users are different from the ones used for enterprise users, you'll probably end up with different IDs for the same user when connected from different methods (e.g. DOMAIN\bla and bla.blason#outlook.com). If you intend to provide both authentication methods at the same time, you have to account for that (for example, by creating a "user" table that has one column for Microsoft account IDs, and one for Domain SIDs). It usually makes little sense to provide both authentication methods at the same time, but it's your app.
Hope I helped!
Once i had the similar situation, (A client app need to connect to server with few identity credentials. after the custom authentication , a token will be grant for the client with few claims, then each client request will be validated against the given token) , if you are in something like this, consider this link, it helped me to solve the issue.
http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
Note: you can implement custom authentication, and authorization by extending claimsAuthenticationManager and Claimsauthorizationmanager respectively

ASP.NET Identity automatically register Claims user

We're attempting to build an intranet web application, and we'd like users to be able to just use their domain credentials to sign into our web site and be automatically registered. All the sample code I've seen with Identity shows users going through a registration page on an AccountController, and the UserManager is used to create the user there.
Since we're requiring authentication on all pages, the user is currently just redirected to the domain sign-in (we're currently using an Azure Active Domain), and then returned to our page. It looks like the default behavior of Identity is to not create a User in the application database when this happens, so we wind up with an authenticated Identity and no corresponding User object in our database. Is there a good place to hook into to create this user? What's the best way to create the user? And how does the UserLogin table play into this, I assume it's used somehow to match a ClaimsPrincipal with the application database User?
We're using MVC 5, Entity Framework 6, and WIF 2
When you use Azure Active Directory (Organizational Accounts), the active directory is your user database. Unless you add it specifically, there won't be an AspNetUserLogins table like you get when you configure your application for authentication using Individual Accounts.
I'm making an assumption that you want to create some kind of user table so that you can store user profile data and/or some authorization claims for each user. You can still do this. For example, you may create a table in a SQL Database (or whatever database you want) to store user profile records in. A good extensibility point in your code for this kind of thing is to derive a class from the ClaimsAuthenticationManager and override the Authenticate method. In here, you can inspect the claims for the incoming authenticated user, look up additional profile claims you've stored for the user in your database table, and then add those claims to the claim set for the ClaimsPrincipal. One of the claims you will get from Azure AD in the incoming principal object is an objectidentifier. This would be a good key for your user profile table so you can correctly identify a user on subsequent logins.
An alternative to the user profile table approach I just described that you may want to look into is the ability to extend the Azure AD schema using Graph API. I've not personally tried this technique yet. It's also still in preview. But, the general idea is you can register an extension for your intranet application that would include the additional properties for each user.

Membership System for Website and Mobile Apps

I am currently working on a project that will have a website and apps for mobile devices. I am going to need a way to let users login to my site to view certain areas. I know I will need to build a WCF RESTful service but I am stuck on how to proceed with creating the users. I was originally going to use the built in .NET Membership but the more I read about it the worst it sounded if I had a lot of users. I then was thinking of building a new provider which would give me all the functionality of the built in .NET Membership but I would have more control over everything. The last idea was to build a whole membership system, but I was worried I would loose the functionality of the built in .NET Membership system. I am basically just looking for someone to point me in the right direction and explain why.
Right now I am thinking the best way to handle this is going to be to build a whole membership system. I am thinking I am going to have my data access all through a WCF in the backend that my website would call and the RESTful service would call. I am not aware of a way right now that I can authenticate a users username and password through a WCF.
Thanks for all your input.
We do this very thing in several of our projects, here is a summary of how we accomplish it. Keep in mind it's only one method, and we have also had success writing our own membership provider.
We have 3 main projects:
Data.project - class library
WebApp.project - MVC Application
API.project - WCF service
We use the built in .NET membership provider as it exists out of the box. This gives us the basic registration, password changes, role management, and the easy controller based role permission and access control in our MVC and API projects.
The default membership provider will use its own tables to store the user data.
We then create our own User and Profile tables and data structure with a foreign key back to the .NET membershipId of the user. This gives us the flexibility to do all of the application specific things we need to do with a user profile while still giving us access to the default provider.
Authentication is straight forward in the MVC project, you can now use the .NET Membership methods to authenticate by username and password:
if(Membership.ValidateUser(username,password)){
FormsAuthentication.SetAuthCookie(username,password);
}
For the WCF project you do not have the luxury of FormsAuthentication, but you can still use the default membership provider to validate the users credentials.
How you handle authentication after that is up to you and your project, but for basic needs we generally go with an authentication token that is returned by the WCF service after validation. This token is then included with each WCF request to prove they have been validated, usually in the request headers.
For WCF we base 64 encode the username and password when submitting the credentials to the server, then if successful we pass back the auth token:
string decoded = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(Authmodel));
//convert your string into your authentication model here then
if(Membership.ValidateUser(model.user,model.pass))
{
//return new authentication token
}
We also include additional logic during registration that build out our proprietary user and profile tables at that time, this is handled in the data project so that both the WCF and MVC may access it.
Additionally, the data project handles the linking between our user and profile tables and that of the .NET Membership provider tables so the information can be accessed by both applications.
I realize that is all quite vague, but maybe it can help you think of one option for handling authentication in a unified way. If you have questions about a specific portion let me know and I hope this information is useful for you.

Facebook authentication and Asp.Net Membership

I'm trying to integrate facebook authentication with an asp.net site.
So if a user decides to register at the site they can do so by using their facebook credentials.
I'm currently at the point where I have the facebook access token and the user details and not sure how I should go from here.
The site uses asp.net membership authorization.
This is what I believe should happen in case a new user decides to register: (But not sure if this the the way to go)
0) User visits the site and decides to register using their facebook credentials.
1) The user providers their credentials and I receive an access token and their user information.
2) I store this information in my database and create an asp.net membership user with the data I received. (At this point I'd have to generate a password).
3) Log the user into the site so he can navigate freely.
I would appreciate some advice if I'm on the correct path and how I should go about generating the password. (I'm thinking in maybe combining the email and facebook userId, retrieve a hash and store.)
Thanks
UPDATE 1
I found this SO question where they suggest to use:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie(v=VS.90).aspx
I think you approach is sound; what you effectively do is to replace the username/password authentication with the received facebook id, and let that id pass as a valid identifier in you application.
You say that you will need to generate a password in you application which I am note entirely sure about. It is true that you will need to create your user with a password as far as the membership provider in ASP.NET is concerned, but you could choose to fill in a random string if you only want the users to login using facebook connections.
Deciding which facebook attribute to bind to is also worth a bit of concideration. The natural choice is of course the facebook identifier since that is unqiue to the user, but if you choose to allow other authentication mechanisms later on - google open id for one - you might also benefit from storing the email from facebook etc.
Probably it will also be a good idea to auto generate a user name in you application that is not defined by facebook. If you choose the facebook identifier as login name you have a hard dependency on facebook making the introduction of new identity providers hard. If you choose a random identifier and an associative table establishing the connection between the facebook id and your id, you will also gain some flexibility later on. Choosing the somewhat more limiting email address might be a better choice if you want to have meaningful output from ASP.NET Login-controls like LoginStatus etc.
I haven't read the response below/above so this may have been covered but be warned that I ran into a serious problem with cookies not being set from within an iframe in IE. It was a bloody nightmare. I'm not sure if this has been fixed, if its fixable, but just be conscious of my experience and test thoroughly in all browsers.
Also checkout the .net open auth project. I haven't used it personally but it supposedly supports OAuth as well as OpenId & ICards, which could be helpful later on for additional integration points.

Categories

Resources