DB-First authentication confusion with ASP.NET Web API 2 + EF6 - c#

I need to create a Web API C# application for an existing MySQL database. I've managed to use Entity Framework 6 to bind every database table to a RESTful API (that allows CRUD operations).
I want to implement a login/registration system (so that I can implement roles and permissions in the future, and restrict certain API requests).
The MySQL database I have to use has a table for users (called user) that has the following self-explanatory columns:
id
email
username
password_hash
It seems that the de-facto standard for authentication is ASP.Net Identity. I have spent the last hour trying to figure out how to make Identity work with an existing DB-First Entity Framework setup.
If I try to construct ApplicationUser instances storing user instances (entities from the MySQL database) to retrieve user data, I get the following error:
The entity type ApplicationUser is not part of the model for the current context.
I assume I need to store Identity data in my MySQL database, but couldn't find any resource on how to do that. I've tried completely removing the ApplicationUser class and making my user entity class derive from IdentityUser, but calling UserManager.CreateAsync resulted in LINQ to Entities conversion errors.
How do I setup authentication in a Web API 2 application, having an existing user entity?

You say:
I want to implement a login/registration system (so that I can
implement roles and permissions in the future, and restrict certain
API requests).
How do I setup authentication in a Web API 2 application, having an
existing user entity?
It definitely means that you DO NOT need ASP.NET Identity. ASP.NET Identity is a technology to handle all users stuffs. It actually does not "make" the authentication mechanism. ASP.NET Identity uses OWIN Authentication mechanism, which is another thing.
What you are looking for is not "how to use ASP.NET Identity with my existing Users table", but "How to configure OWIN Authentication using my existing Users table"
To use OWIN Auth follow these steps:
Install the packages:
Owin
Microsoft.AspNet.Cors
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.Owin
Microsoft.AspNet.WebApi.WebHost
Microsoft.Owin
Microsoft.Owin.Cors
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security
Microsoft.Owin.Security.OAuth
Create Startup.cs file inside the root folder (example):
make sure that [assembly: OwinStartup] is correctly configured
[assembly: OwinStartup(typeof(YourProject.Startup))]
namespace YourProject
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
//other configurations
ConfigureOAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/security/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
Provider = new AuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
try
{
//retrieve your user from database. ex:
var user = await userService.Authenticate(context.UserName, context.Password);
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
//roles example
var rolesTechnicalNamesUser = new List<string>();
if (user.Roles != null)
{
rolesTechnicalNamesUser = user.Roles.Select(x => x.TechnicalName).ToList();
foreach (var role in user.Roles)
identity.AddClaim(new Claim(ClaimTypes.Role, role.TechnicalName));
}
var principal = new GenericPrincipal(identity, rolesTechnicalNamesUser.ToArray());
Thread.CurrentPrincipal = principal;
context.Validated(identity);
}
catch (Exception ex)
{
context.SetError("invalid_grant", "message");
}
}
}
}
Use the [Authorize] attribute to authorize the actions.
Call api/security/token with GrantType, UserName, and Password to get the bearer token. Like this:
"grant_type=password&username=" + username + "&password=" password;
Send the token within the HttpHeader Authorization as Bearer "YOURTOKENHERE". Like this:
headers: { 'Authorization': 'Bearer ' + token }
Hope it helps!

Since your DB schema are not compatible with default UserStore You must implement your own UserStore and UserPasswordStore classes then inject them to UserManager. Consider this simple example:
First write your custom user class and implement IUser interface:
class User:IUser<int>
{
public int ID {get;set;}
public string Username{get;set;}
public string Password_hash {get;set;}
// some other properties
}
Now author your custom UserStore and IUserPasswordStore class like this:
public class MyUserStore : IUserStore<User>, IUserPasswordStore<User>
{
private readonly MyDbContext _context;
public MyUserStore(MyDbContext context)
{
_context=context;
}
public Task CreateAsync(AppUser user)
{
// implement your desired logic such as
// _context.Users.Add(user);
}
public Task DeleteAsync(AppUser user)
{
// implement your desired logic
}
public Task<AppUser> FindByIdAsync(string userId)
{
// implement your desired logic
}
public Task<AppUser> FindByNameAsync(string userName)
{
// implement your desired logic
}
public Task UpdateAsync(AppUser user)
{
// implement your desired logic
}
public void Dispose()
{
// implement your desired logic
}
// Following 3 methods are needed for IUserPasswordStore
public Task<string> GetPasswordHashAsync(AppUser user)
{
// something like this:
return Task.FromResult(user.Password_hash);
}
public Task<bool> HasPasswordAsync(AppUser user)
{
return Task.FromResult(user.Password_hash != null);
}
public Task SetPasswordHashAsync(AppUser user, string passwordHash)
{
user.Password_hash = passwordHash;
return Task.FromResult(0);
}
}
Now you have very own user store simply inject it to the user manager:
public class ApplicationUserManager: UserManager<User, int>
{
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyDbContext>()));
// rest of code
}
}
Also please note you must directly inherit your DB Context class from DbContext not IdentityDbContext since you have implemented own user store.

Related

How to inject a ClaimsPrincipal in a Blazor Server application

Here are some artifacts to help understand the issue:
Sample Code - Github repo
Deployed Application - no longer available
Update: I have followed this YouTube video which I now believe to be the correct way of accessing information about the authenticated user in dependent services for a Blazor Server application: https://www.youtube.com/watch?v=Eh4xPgP5PsM.
I've updated the Github code to reflect that solution.
I have the following classes that I register using dependency injection in my ASP.NET MVC Core application.
public class UserContext
{
ClaimsPrincipal _principal;
public UserContext(ClaimsPrincipal principal) => _principal = principal;
public bool IsAuthenticated => _principal.Identity.IsAuthenticated;
}
public class WrapperService
{
UserContext _userContext;
public WrapperService(UserContext context) => _userContext = context;
public bool UserHasSpecialAccess()
{
return _userContext.IsAuthenticated;
}
}
The IoC dependency registrations are configured in Startup.cs
services.AddScoped<ClaimsPrincipal>(x =>
{
var context = x.GetRequiredService<IHttpContextAccessor>();
return context.HttpContext.User;
});
services.AddScoped<UserContext>();
services.AddScoped<WrapperService>();
I recently enabled Blazor in the MVC application and wanted to use my DI registered services from within my Blazor components.
I injected the service in a Blazor component in order to use it like so:
#inject WrapperService _Wrapper
However, when I attempt to use the service from a server side handler, the request fails with an exception complaining that the services could not be constructed - due to IHttpContext not existing on subsequent calls to the server.
<button #onclick="HandleClick">Check Access</button>
async Task HandleClick()
{
var hasPermission = _Wrapper.UserHasSpecialAccess(); // fails 😔
}
I think I understand why the use of IHttpContextAccessor is not working/recommended in Blazor Server apps. My question is, how can I access the claims I need in my services without it?
The odd thing to me is that this all works when I run it under IIS Express in my development environment, but fails when I deploy and attempt to run it from within an Azure AppService.
This is what work for me, writing a derived class for AuthenticationStateProvider.
public class AppAuthenticationStateProvider : AuthenticationStateProvider
{
private ClaimsPrincipal principal;
// Constructor, only needed when injections required
public AppAuthenticationStateProvider(/* INJECTIONS HERE */)
: base()
{
principal ??= new();
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
return Task.FromResult(new AuthenticationState(principal));
}
// Method called from login form view
public async Task LogIn(/* USER AND PASSWORD */)
{
// Create session
principal = new ClaimsPrincipal(...);
var task = Task.FromResult(new AuthenticationState(principal));
NotifyAuthenticationStateChanged(task);
}
// Method called from logout form view
public async Task LogOut()
{
// Close session
principal = new();
var task = Task.FromResult(new AuthenticationState(principal));
NotifyAuthenticationStateChanged(task);
}
Then, at program/startup you add these lines:
// Example for .Net 6
builder.Services.AddScoped<AuthenticationStateProvider, AppAuthenticationStateProvider>();
builder.Services.AddScoped<ClaimsPrincipal>(s =>
{
var stateprovider = s.GetRequiredService<AuthenticationStateProvider>();
var state = stateprovider.GetAuthenticationStateAsync().Result;
return state.User;
});
That's it. Now you can inject ClaimsPrincipal wherever you want.
You can inject AuthenticationStateProvider into your Service constructor and then use
var principal = await _authenticationStateProvider.GetAuthenticationStateAsync();
AuthenticationStateProvider is a Scoped service so yours has to be too.
Use CascadingAuthenticationState to access the claims principal
https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0#expose-the-authentication-state-as-a-cascading-parameter-1
If you need to use your own logic, you will need to implement your own authentication state provider.
If you want to use a service to use ClaimsPrincipal you can do the following:
ClaimsPrincipalUserService.cs
ClaimsPrincipal claimsPrincipal;
void SetClaimsPrincipal(ClaimsPrincipal cp)
{
claimsPrincipal = cp;
// any logic + notifications which need to be raised when
// ClaimsPrincipal has changes
}
Inject this service as scoped in the startup.
In the layout
MainLayout.razor
#inject ClaimsPrincipalUserService cpus;
[CascadingParameter]
public Task<AuthenticationState> State {get;set;}
protected override async Task OnInitializedAsync()
{
var state = await State;
var user = state.User; // Get claims principal.
cpus.SetClaimsPrincipal(user);
}

ASP.NET Core 2 authorization from database table

I have a series of web pages and the authorization to those pages is defined in a custom database table. For example, I have a role called "superuser" and that role is allowed access on certain web pages. I have users assigned to that role.
I don't understand how I can put an Authorize attribute on a controller and pass in a page name (a view) and then have a custom handler of some type read from my database to see if the user is in a group that has permission. I've been reading up on policy-based authorization here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.2 and trying to make sense of it for my situation.
Am I on the right track with policy based authorization or is there another way to do a database check for permission before allowing the user to access the page?
The Authorize attribute, in itself, only serves to specify the kind of authorization you need on a particular page or controller. This attribute is meant to be used in addition to the Identity framework, and can include roles, policies, and authentication schemes.
What you need is to create a bridge between the Identity framework and your database, which can be accomplished with custom UserStore and RoleStore, which is described in details on this page.
To summarize a pretty complex process:
The Authorize attribute instructs the browser to authenticate your user
Your user is redirected to the authentication page
If it succeeds, you're provided with a ClaimsPrincipal instance, that you then need to map to your database user, via the custom UserStore
Your user can then be checked against DB roles
Here's a short example of all this in action (NOT fully complete, because it would be far too much code).
Startup.cs
// This class is what allows you to use [Authorize(Roles="Role")] and check the roles with the custom logic implemented in the user store (by default, roles are checked against the ClaimsPrincipal roles claims)
public class CustomRoleChecker : AuthorizationHandler<RolesAuthorizationRequirement>
{
private readonly UserManager<User> _userManager;
public CustomRoleChecker(UserManager<User> userManager)
{
_userManager = userManager;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement)
{
var user = await _userManager.GetUserAsync(context.User);
// for simplicity, I use only one role at a time in the attribute
var singleRole = requirement.AllowedRoles.Single();
if (await _userManager.IsInRoleAsync(user, singleRole))
context.Succeed(requirement);
}
}
public void ConfigureServices(IServiceCollection services)
{
services
.AddIdentity<User, Role>()
.AddUserStore<MyUserStore>()
.AddRoleStore<MyRoleStore>();
// custom role checks, to check the roles in DB
services.AddScoped<IAuthorizationHandler, CustomRoleChecker>();
}
where User and Role are your EF Core entities.
MyUserStore
public class MyUserStore : IUserStore<User>, IUserRoleStore<User>, IQueryableUserStore<User>
{
private Context _db;
private RoleManager<Role> _roleManager;
...
public async Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
{
// bridge your ClaimsPrincipal to your DB users
var user = db.Users.SingleOrDefault(_ => _.Email.ToUpper() == normalizedUserName);
return await Task.FromResult(user);
}
...
public async Task<bool> IsInRoleAsync(User user, string roleName, CancellationToken cancellationToken)
{
if (roleName == null)
return true;
// your custom logic to check role in DB
var result = user.Roles.Any(_ => _.RoleName == roleName);
return await Task.FromResult(result);
}
.Net Core -> if you going to use policy based approach, You have to define policy definition in ConfigureServices method in startup.cs
Example:
services.AddAuthorization(options =>
{
options.AddPolicy("UserPolicy", policy => policy.RequireRole("USER"));
});
Then u can apply the policy like below in controller or action method.
Authorize(Policy = "UserPolicy")

ASP.NET Core MVC custom identity properties

I am trying to build a website in ASP.NET Core MVC and am using the Microsoft.Identity library. I have a custom property in my User (ApplicationUser) class which is called Token. I want to create a cookie on login with that token. So I need to call some function that allows me to fetch the Token attribute from the logged in user (via UserManager or whatever. It has to be the user that logged in.)
I have searched on the internet and have found several solutions by creating a custom Factory and then adding it to the startup.cs Like this. But I cannot find or see a way to access the property. User.Identity.GetToken() does not work.
Here is my custom factory:
public class CustomUserIdentityFactory : UserClaimsPrincipalFactory<User, IdentityRole>
{
public CustomUserIdentityFactory(UserManager<User> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{}
public override async Task<ClaimsPrincipal> CreateAsync(User user) {
var principal = await base.CreateAsync(user);
if(!string.IsNullOrWhiteSpace(user.Token)) {
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(ClaimTypes.Hash, user.Token)
});
}
return principal;
}
}
Here is the configure in my Startup.cs
services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomUserIdentityFactory>();
So, long story short: I am trying to access a custom identity property and have found a way to add it to the UserManager, but can not find a way to access it.
Your "CustomUserIdentityFactory" adding claims to the logged in user, so that claims will be added in to the cookie, which can be accessed using "User.Claims" by specifying your claim type.
Assume your claim type is "http://www.example.com/ws/identity/claims/v1/token"
Change your code as below by overriding "CreateAsync" method using your own claim type.
public override async Task<ClaimsPrincipal> CreateAsync(User user) {
var principal = await base.CreateAsync(user);
var tokenClaimType = "http://www.example.com/ws/identity/claims/v1/token"
if(!string.IsNullOrWhiteSpace(user.Token)) {
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim(tokenClaimType, user.Token)
});
}
return principal;
}
How to access token as part of "User.Claims"
var tokenClaimType = "http://www.example.com/ws/identity/claims/v1/token"
var token = User.Claims.Where(claim => claim.Type == tokenClaimType);
Hope this helps.

How to get users from a existing database for identityServer4

i try to understand how i can bind users (email, password, firstname, lastname and os on) which are stored in an existing database (located: localhost:3306) into my identityserver4 project so that i can use these information to login a user or register a new user into that database?
I read some tutorials (specially http://docs.identityserver.io/en/release/quickstarts/8_entity_framework.html) but i think this is always for db in the same project. my db isn´t in the same project.
In this context i read about asp.net-core Identity. but i don´t understand completely how that´s related.
Can someone tell me how can i bind a db in my project and what´s the role of identity with application User and so on?
thanks in advance
This article is more relevant to your situation. The one you linked is for configuration data and not for user data:
http://docs.identityserver.io/en/release/quickstarts/6_aspnet_identity.html
In short, you want to access your user data through Asp.Net Core Identity.
You need to:
Make a user class containing the relevant fields as your database
Create an EntityFramework DbContext class to map your database to your class
Register your user class and dbcontext with aspnet core identity
Tell IdentityServer to use AspNetIdentity
This is what your Startup ConfigureServices method might look like once implemented. Not pictured here is the DbContext and User classes you need to make.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<YourUserStoreDbContextHere>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<YourUserClassHere, YourRoleClassHereIfAny>()
.AddEntityFrameworkStores<YourUserStoreDbContextHere>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
// Other config here
.AddAspNetIdentity<YourUserClassHere>();
}
Refer to the docs on AspNet Identity for details on configuring your user class and dbcontext: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity
You need to implement your own UserStore (example)
public async Task<TapkeyUser> ValidateCredentialsAsync(string username, string password)
{
//This is pseudo-code implement your DB logic here
if (database.query("select id from users where username = username and password = password")
{
return new User(); //return User from Database here
} else {
return null;
}
}
And use this in your AccountController:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model)
{
if (ModelState.IsValid)
{
// use our custom UserStore here
--------> if (_users.ValidateCredentials(model.Username, model.Password))
{
AuthenticationProperties props = null;
// only set explicit expiration here if persistent.
// otherwise we reply upon expiration configured in cookie middleware.
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
{
props = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
};
// issue authentication cookie with subject ID and username
var user = _users.FindByUsername(model.Username);
await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));
await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);
// make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return Redirect("~/");
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));
ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await _account.BuildLoginViewModelAsync(model);
return View(vm);
}

OWIN WebAPI 2 Bearer authentication custom identity

I want to allow two types of authentication on my site :
* Forms authentication: The user login using his/her details in the form. The authentication should be made using cookies.
* Bearer: When calling WebAPI's (for mobile), the authentication should be made only by using bearer tokens.
I've relayed on the SPA template and some questions in SO and did successful made it available.
The only problem I'm facing is the ClaimsIdentity: I wish to use custom identity class. However, I'm being able to do so only in forms authentication, not in bearer WebAPI requests.
My custom identity:
public class MyIdentity : ClaimsIdentity, IMyIdentity
{
#region IMyIdentity
private Account _account = null;
public Account Account
{
get
{
if (_account == null)
{
if (this.IsAuthenticated)
{
Guid claimedAccountId = Guid.Parse(this.FindFirst(ClaimTypes.NameIdentifier).Value);
var accountService = ServiceLocator.SharedInstance.GetInstance<IAccountService>();
_account = accountService.Where(
a => a.Id == claimedAccountId
).FirstOrDefault();
}
_account = _account ?? Membership.Account.GuestAccount;
}
return _account;
}
}
#endregion
}
In Global.asax, I've overridden the Application_OnPostAuthenticateRequest method in order to set the custom identity, and it does working good - but only in forms, not in WebAPI.
In addition, I do set in WebApiConfig.cs
config.SuppressDefaultHostAuthentication();
so it does make sense that MyIdentity being nulled and User.Identity resets back to ClaimsIdentity.
So to sum up my question - is there a way to define which Identity class will be used, so I can set MyIdentity instead of ClaimsIdentity?
For Web API, you could try hooking into the OWIN authentication pipeline, and implement your own Authentication Filter, and use it to change the current principal to your own:
public class MyAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
public Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken)
{
if (context.Principal != null && context.Principal.Identity.IsAuthenticated)
{
CustomPrincipal myPrincipal = new CustomPrincipal();
// Do work to setup custom principal
context.Principal = myPrincipal;
}
return Task.FromResult(0);
}
And register the filter:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new MyAuthenticationFilter());
...

Categories