IdentityServer4 + Asp Identity + EF Configure two UsersSet/Providers - c#

Having trouble finding a good lead on this. I have a aspnetcore app with identityserver4 configured to use asp identity with a sql database.
There is a business requirement that all non AD users are stored in this asp identity database.
All AD users are defined on Azure. I can authenticate them with LDAP and receive their data.
The issue comes after authentication. Whenever asp identity tries to call:
var user = await UserManager.FindByNameAsync(userName);
With an AD user, it fails because the user does not exist. This is because it is using EF to query the asp identity database, where those users are not defined.
private DbSet<TUser> UsersSet { get { return Context.Set<TUser>(); } }
I can not store any of the AD information in the asp identity database (business requirement). I am trying to find a way to get the user store to look both at the asp identity tables, as well as Azure (via LDAP).
My current method for getting the AD users when doing initial auth is here:
await GetADUser(queryParams),
It uses LDAP to authenticate and grab the user object.
One additional requirement is that I can not use an external login screen, the login must all be done from the same company facing login UI. AKA no external providers.

As per #mxmissile, abstracting the UserManager out was the correct call. Then you can also abstract out other managers as needed for special functionality. This is in fact the only class in the inheritance layer for this part of the code that is virtual.
There are built in functions that let you register your custom managers:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddUserManager<ApplicationUserManager<IdentityUser>>()
.AddSignInManager<ApplicationSignInManager<IdentityUser>>()
Hopefully this is a little help to any others that have a similar question. I ended up just overriding a couple of the functions from the base user manager and just calling the base method for anything that did not need my new logic. By default it looks like ASP Identity does not try to look up users by email - just fyi.

Related

Custom role based authorization from an existing database

Currently, I am developing an web application in ASP.net and till now i have done authenticating the user after successful login using Identity in ASP.Net. Now i want to authorize the user based on the different roles available in the database. I have a database with 3 tables namely Users, Roles and UserRoles. A user can have more than 1 role.
In this case, how can i implement role based authorization in my project.I have done custom authentication using Identity and removed Entity from my project.
public void ConfigureAuth(IAppBuilder app)
{
// Configure the custom user manager and custom signin manager to use a single instance per
request
app.CreatePerOwinContext<CustomUserManager>(CustomUserManager.Create);
app.CreatePerOwinContext<CustomSignInManager>(CustomSignInManager.Create);
}
With this, simple[Authorize] attribute is working fine for me. How can i create something like [Authorize(Roles="Customer")]? Should i use something like IRole for this or just overriding Authorize Attribute method is enough? Is both same or different? Can anyone help me to solve this problem?

ASP.NET Web API with Bearer authentication. How to get/add/update unique user data?

Currently I am about to develop my first REST web API!
I'm currently designing how the system will work yet I am a little confused how things are going to work.
Primarily, a mobile app will consume the Web API, but it must be secure!
For example I wouldn't want an un-authed request handled at all. (Apart from a user registering)
I have found that I can use SSL + Bearer tokens to achieve this user authentication. I am comfortable with this and have tested to see how this would work. And it's suitable.
The problem arises when I wish to retrieve the user details.
In my system a user would log in to the mobile app which would request the token from the server. If all is good, I can log the user into the app. Great! Now, I need to get the information stored about this user to present to them. i.e. name, email, reward points etc...
I am unfamiliar with how to add extra user data AND retrieve it with the Web API. I understand that the token can be used to uniquly identify a user. but how can I extend this data?
Currently I have not much more than a blank WebAPI project with the bearer token authentication implemented. Still using the Entity framework. How can I add more fields of data to a user record?
Furthermore, how can I update these records? For example, a user has gained some reward points, how can update the user data for this?
One final question, Is this suitable for retaining per user data? i.e. can I link other data to a userID or something similar?
Apologies for sounding over-curious, I am very new to MVC
The below code in the IdentityModel.cs would seem like the appropriate place to add user data, but how do I add to this? for example adding a field for reward points? then how would I update upon it?
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
}
How I would do it:
Create ActionFilter that would validate token, it would use your custom class that would leverage DI, it would obviously get the user ID as well
Now that you know that user is authenticated and you know the user ID just do your regular CRUD based on this user ID
Note: Remember to also validate the payload, since if I send you PUT: /user/887/points {points: 999} I could potentially gain unlimited points.
It's not necessary to use ASP .NET Identity for implementing security in your web API project.
If you use Identity you will have to stick on to "ApplicationUser" and Identity tables for user management where you won't be able to complete your requirement.
A solution is to handle user management with your own custom table and implement security using OWIN middleware classes available for .NET, ie, you need to write code for generating and validating tokens rather than using Identity.

How in ASP.NET MVC do I maintain info about whether a user is "logged in" throughout pages?

After they type in their password, should I keep a variable in server session storage like Session["loggedIn"] = true that I check when requests are made to pages that require a login, or is there a better/safer way this is traditionally done in ASP.NET?
No, do not keep this in a session variable. In fact, I would argue you should try not to use session for anything. Try to keep the HTTP communication as stateless as possible.
For authentication in ASP.NET MVC, you have 2 alternatives, but ultimately, the both end up working the same way: by writing an encrypted authentication cookie to the browser after you successfully log a user in.
The newer alternative was mentioned in a comment to the OP: Microsoft.AspNet.Identity. To use this, you should be using a newer version of ASP.NET MVC with the OWIN pipeline (though I am not sure if you have to). The older alternative is called Forms Authentication, and can be used with any version of MVC except version 6 (the new vNext / core 1.0 stuff) I believe.
When you have successfully integrated one of these 2 tools into your MVC application, after a user logs on, your Controllers will have a non-null User property of type IPrincipal. You can use this property to determine whether or not a user is authenticated:
// in a controller
bool isThereAUserLoggedIn = this.User != null && this.User.Identity.IsAuthenticated;
If you are using the newer Microsoft.AspNet.Identity, then this IPrincipal User property will be implemented as a ClaimsPrincipal with one or more ClaimsIdentitys. Forms Authentication does not do claims like this, so if you want claims, or social login, etc, use Microsoft.AspNet.Identity.
The way that this is traditionally done in ASP.NET and by my opinion also better and safer is by making use of the ASP.NET Identity package.
ASP.NET Identity handles all aspects around user accounts in a web application:
database for users, including roles and more
user registration and management, like register, email verification, log in, remember me option, forgot my password action and more.
user authentication & authorization
Just to make things more clear, authentication means that the user making the request is actually a valid application user and authorization means that the user has the authority to perform the requested action.
Practically, when a user logs in, Identity automatically keeps that information and makes it available in all controllers and views under User property. So you know at any time which user made the request. Identity also supplies each request with a cookie used for user authentication and authorization.
To check for user authentication you use the User.Identity.IsAuthenticated in a view and the Authorize attribute in a controller:
[Authorize]
public ActionResult Create( ... ){ ... }
The above use of the Authorize attribute will allow only to registered users to request this page.
It is also very common to extend the functionality of your application to include roles for the users and user authorization. Identity creates a "Users" table, a "Roles" table and a many to many relationship between them. After assigning roles to your users you can authorize their requests by using User.Identity.IsInRole("YourRoleName") in a view and in a controller:
[Authorize("YourRoleName")]
public ActionResult Create( ... ){ ... }
The above use of the Authorize attribute will allow only to registered users having the "YourRoleName" role to request this page. In any case if Identity fails to authenticate or authorize the request will prompt to the log in page.
ASP.NET Identity is simple to use, it works and it is easy to extend the membership functionality of your application both by making use the many tools supplied with it and overriding its classes to give them a more specific or complex behaviour.
You will find infinite help on the web on how to use it or a step by step guide.

Web API token authentication with a custom user database

I am developing a Web API 2.1 service that needs to authenticate the connecting clients (HTML5/JS clients that I will create and control). Unfortunately, the user information (username, password hashes, roles and much, much more info) is stored in an existing (SQL Server) database to which I only have read access. The Users database table was created 5-6 years ago without any reference to security frameworks, so it's a completely custom format. I'm not allowed to make any changes to either the data or the database structure.
Inspired by this article, I rolled my own token-based method of authenticating users, but I'm lacking the completeness and (re)assurance of using an established security framework.
Is there a way to integrate an existing framework, e.g. OAuth2, within my current project given the constraints I mentioned above? I don't know if it makes any difference, but I'm self-hosting using OWIN.
This is a good answer to a similar question.
It basically says:
Make a custom user class which implements IUser
Define a custom user store which implements public class UserStoreService
: IUserStore<CustomUser>, IUserPasswordStore<CustomUser>
wire everything up
Since the answer is pretty extensive I just provided the basic steps...
details are here: How to customize authentication to my own set of tables in asp.net web api 2?
This is also a very valuable content which also applies to web api:
Customizing ASP.NET Authentication with Identity by JumpStart
https://channel9.msdn.com/Series/Customizing-ASPNET-Authentication-with-Identity
HTH
Someone else, having the competence, can explain the options. But if authentication as service is an option, then check out Auth0 # https://auth0.com
I have tested the service (as Azure plugin) using both HTML/JS- and native Windows Phone applications, against simple Sql Server table and AD. Works liek charm, near zero headache.
I stumbled upon a my solution while trying to implement json token authentication within web api. It is important to note that my solution handles authentication by sending a json token through the Authentication header of the Http request (not via cookies) and not using Microsoft.Identity framework.
Anyway, I basically implemented in a cookbook fashion the solution helpfully described here by Taiseer Joudeh: http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/
The key thing to notice is the following bit of code:
//Dummy check here, you need to do your DB checks against memebrship system http://bit.ly/SPAAuthCode
if (context.UserName != context.Password)
{
context.SetError("invalid_grant", "The user name or password is incorrect");
//return;
return Task.FromResult<object>(null);
}
Naturally you would replace this bit of code above with your own method for checking your (presumably pre-existing) user database(s). Once I implemented this I realized that you don't need to use new code first identity framework that Visual Studio installs for you.
To make this work I did the following:
1) Created an an empty project and selected Change Authentication/Individual User Accounts. This installs most of the required references and files you need out of the box to use token authentication by way of cookies as well as the code-first identity framework files.
2) Edited these files following Taiseer Joudeh's lead. This requires
some new objects such as CustomOAuthProvider.cs among others. And you need to implement your own user/password check by customizing this code block:
if (context.UserName != context.Password)
{
context.SetError("invalid_grant", "The user name or password is incorrect");
//return;
return Task.FromResult<object>(null);
}
Link to Taiseer Joudeh's instructions: http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/
3) Pruned my project of extraneous files (AccountBindingModels.cs, AccountViewModels.cs, IdentityModels.cs, ApplicationOAuthProvider.cs, identityConfig.cs, AccountBindingModels.cs, AccountViewModels.cs). Basically, No more microsoft identity references.
I am sure the microsoft.identity thing is excellent, but I was annoyed with the code-first implementation of databases when I was already using some legacy databases of a different structure etc. Hope this helps. I am quite satisfied with the result (after a few days of messing around to get it to work).
I did not want to use any existing classes and finally come out some thing very simple like
var userName = context.UserName;
var password = context.Password;
var userService = new UserService(); // our created one
var user = userService.ValidateUser(userName, password);
if (user != null){
.......
}
See the full details here OAuth Web API token base authentication with custom database
For Role base authentication with custom database
Hope it will help
This might be a completely insane and invalid approach for you but I faced a similar challenge: New web app (MVVM + WebAPI), legacy system used to issue and validate tokens. Inspired by http://tech.pro/tutorial/1216/implementing-custom-authentication-for-aspnet, and because my application would primarily be used by its accompanied GUI (the MVVM webapp), I decided to use a "cookie based" token produced by FormsAuthentication. The FormsAutnentication cookie/ticket is secured by .net internal magic security (which I assume id completely safe and unbreakable).
In my case the cookie simply holds the ticket issued by the legacy system, (but you could store more details there as well, eg by JSONSerializing a custom type). During authorization, my system validates the token against the legacy system. I guess you could use something similar together with a custom AuthorizationFilter.

Is it worth to move to SimpleMembership

I have a project that is not released yet I will not be soon but I moved it from mvc3 to mvc4 a few days ago and while reading I saw this new security provider SimpleMembership.
The way I implement security now is by using MembershipProvider and FormsAuthentication:
I have implemented ICustomPrincipal
I have implemented CustomPrincipalSerializeModel
I have implemented IPrincipal
To register user I use:
MembershipCreateStatus status;
Guid g = Guid.NewGuid();
Membership.CreateUser(model.User.Email.Trim(), model.Password.Trim(), model.User.Email.Trim(), null, null, true, g, out status);
if (status == MembershipCreateStatus.Success)
...
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
tUser.Email,
DateTime.Now,
DateTime.Now.AddDays(60),
true,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
...
But as I saw SimpleMembership looks much cleaner and I want to move project to it
but I have some questions about it:
1) I use stored procedures for all database actions I don't use EF at all. If I use SimpleMembership is it possible to use it without EF?
2) Do I need to build custom SimpleMembership for real world application?
3) I saw that it seeds database Create tables. I have my tables Users, Profiles, Roles and UsersInRoles can I apply it to my custom schema?
4) If I want to call WebSecurity.CreateAccount(...) and I want to call some my custom method from domain project that is responsible to call stored procedure that create user do I have to make it custom and if I have to do that is there some resource that explain how to make it custom for users and roles?
To understand SimpleMembership and how it has evolved from, and depends on, the previous Membership implementation, I recommmend reading the original reference "Using SimpleMembership With ASP.NET WebPages (Matthew Osborn)", and my more detailed answer to "What is MVC4 security all about?" to understand it better. To summarise those references:
SimpleMembership
is a term that covers both the SimpleMembershipProvider and the SimpleRoleProvider
is a storage and functionality provider that is used with Forms Authentication
works within ASP.NET Forms and ASP.NET MVC websites, and can also be used within ASP.NET Web API and SignalR, to provide a unified authentication and authorisation model
SimpleMembershipProvider
adds new features to the original MembershipProvider through the ExtendedMembershipProvider abstract base class, such as integration with OAuth providers out of the box
creates 4 default tables which you don't/shouldn't interact with (webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_UsersInRoles) and one (UserProfile) which is yours to structure as you wish
works with the WebSecurity helper class to add new functionality
Moves from the "user profile" stored in a single xml field in the original Membership, to a more manageable property-per-column in the new UserProfile table (which is fully customisable using EF)
To answer your specific questions:
1) I use stored procedures for all database actions I don't use EF at all. If I use SimpleMembership is it possible to use it without EF?
You would not generally interact directly with the tables prefixed with webpages_ as there are API level functions in Membership, WebSecurity etc. to do all the business functions you require. However there is nothing to stop you interacting with UserProfile through stored procedures, and if you didn't want to take advantage of the APIs, you could even interact with the webpages_ tables through sprocs as well (but you would just be duplicating all the benefits of SimpleMembership if you did).
2) Do I need to build custom SimpleMembership for real world application?
That very much depends on what you want to do, but as yet I have not had to do this for any real world applications. I have built on and added to the existing APIs, but not replaced them.
3) I saw that it seeds database Create tables. I have my tables Users, Profiles, Roles and UsersInRoles can I apply it to my custom schema?
If you were migrating to SimpleMembership you would have to port the data in these to the tables webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_UsersInRoles and UserProfile. However, note that UserProfile can be called anything you want, you don't have to call it UserProfile.
4) If I want to call WebSecurity.CreateAccount(...) and I want to call some my custom method from domain project that is responsible to call stored procedure that create user do I have to make it custom and if I have to do that is there some resource that explain how to make it custom for users and roles?
Its a little hard to understand your requirement, however WebSecurity.CreateAccount does the following:
Creates a record in webpages_Membership and
optionally adds properties to UserProfile if you use WebSecurity.CreateUserAndAccount
If you wanted to do other actions across your database you would then need to call that after your call to WebSecurity.CreateAccount. You can make this transactional by using TransactionScope
If however you wanted to wrap this all in a single call to WebSecurity.CreateAccount and make it call your own domain methods and stored procedures you will have to create your own provider by inheriting from SimpleMembershipProvider (or from ExtendedMembershipProvider). When WebSecurity.CreateAccount then calls ExtendedMembershipProvider.CreateAccount it will defer to your custom logic
Summary
So would I migrate? The benefits of SimpleMembership are meant to be:
UserProfile: property-per-column storage of user data that plays well with EF or any other db development method
Integration with OAuth, allowing you to use Google, Facebook etc. authentication with very little effort
High level business function APIs in the form of WebSecurity, and continued support of existing features with Membership
Continued support for Roles that works with the Authorize attribute
Integration with EF so that you can use UserProfile along with your own tables
Integration with standard Forms Authentication for ASP.NET Forms and MVC, and also with SignalR and Web API.
If those help you out, then migrate, otherwise spend your dev time on new features for your application.
If you do decide to migrate, then "Migrating Legacy Apps to the New SimpleMembership Provider (Paul Brown)" is useful, which is summarised as:
Modify UserProfile to have a field per property for your old user profile properties that were stored in xml
Migrate your data from the aspnet_ tables to the webpages_ tables
The first time each user logs in again, update their stored password to use the new hash model instead of the old Membership one (see the footnote to my answer here for how to do this)
#Andy Brown makes a lot of good points. I would note to anyone who lands on this that Simplemembership is basically dead and was short lived with ASP.Net Identity coming out shortly after it and is what is used in all new projects. Such a short lived membership product.

Categories

Resources