How to Authenticate users differently in service stack based on service routes? - api

I am using servicestack.
I want to authenticate users differently based on the route in the API.
For example:
If the user is accessing a company route: /api/company (POST) (update to company data) I want to use the master keys stored in super admin account (for example).
But if the user is accessing some trivial data say employee departments, then the authentication of that employee, Route: /api/employees/74274762764/departments (GET)
So how do I do this if I am using Credentials Authentication (inheriting and implementing).
Do I detect the paths and write logic? That will be very brittle.
Theoretically I want to specify attribute on services and provide the authentication needed. So something like:
[CorporateAuthentication] or [UserAuthentication] so the authentication logic can figure out where to validate the user.
Please help.
Thanks
Amit

Normally when you have resources with different levels of accessibility, you don't actually want to Authenticate differently, instead you want the resources protected by varying roles or permissions that are attached on Authenticated users.
There's an example of how to use ServiceStack's Authentication and authorization wiki page:
[Authenticate]
//All HTTP (GET, POST...) methods need "CanAccess"
[RequiredRole("Admin")]
[RequiredPermission("CanAccess")]
[RequiredPermission(ApplyTo.Put | ApplyTo.Post, "CanAdd")]
[RequiredPermission(ApplyTo.Delete, "AdminRights", "CanDelete")]
public class Secured
{
public bool Test { get; set; }
}
This earlier StackOverflow Answer goes into detail of how Roles and Permissions work in ServiceStack.

Related

How should I implement user authentication/roles for an Electron desktop app?

I'm designing the architecture for a college project and I don't know how to deal with the user authentication and authorization part of it. The project is a desktop Electron app which would need two types (hence the roles) of users. They both need to be authenticated in order to use the app, and depending on their identity, they will have different authorizations. Since the project is meant to be used by teachers and students as part of a laboratory class after it is done, I don't think more than 30 people will be using it at the same time.
My first thought was using a PostrgeSQL database in AWS for this and implementing the authentication myself, but this means that users will have to sign up and create a new profile, which means remembering yet another <username/email, password>. Trying to avoid this, I read a bit about OAuth 2.0 and OIDC, and how it can be used to authenticate and authorize users without implementing either of those tasks oneself, but rather delegating the task to OIDC. I created a free account with Auth0 and thought about using it for the OIDC integration but after reading about 40 pages of an "OIDC integration handbook" they offer for free, I could not know if I would be able to distinguish my user base through these roles or tags as I mentioned. I just followed the steps in the tutorial handbook and tried to understand how the auth flow worked, but that didn't give me any information on my question.
So all in all what I want to know is: is it possible to implement this with Auth0 (free account) without having to use a third-party database solution (such as PostgreSQL with AWS)? If not, what would you recommend me to look into? Preferrably a solution that will let me discriminate between the two types of users BUT at the same time taking advantage of the OIDC implementation of Google for example.
There are 2 separate solutions here:
DESKTOP AUTHENTICATION
The 2 standard requirements are:
Use Authorization Code Flow (PKCE)
Login via System Browser
You listen for a login response via one of these mechanisms (I prefer the latter):
Loopback web server
Private URI scheme OS notification
My blog has some tutorials + code samples that use Electron. You can run both of the above listening options and see what you prefer.
API AUTHORIZATION WITH ROLES
You need to make roles available to the API via claims. This can be done by either of these mechanisms (I prefer the latter):
Including roles in access tokens via Auth0
Get the API to read user roles from its own database
My Authorization blog post discusses building up a claims object in an easy to extend way. The main objective is usually for API OAuth processing to result in an object something like this:
class UserPrincipal {
// The technical user id from the access token
string sub;
// The user id from your own database
string userId;
// The user's roles
string[] roles;
}
Given that object you can do things like this:
Use role based authorization when needed
Serve up user resources after login from your application data
TO SUMMARISE
Auth0 will meet some of your requirements and may be all you need in the early days. You will probably need to manage non OAuth user data in your API at some point though.
Happy to answer any follow up questions ..

How to isolate login logic in a separate DbContext with .NET Core Identity

I'm creating a mobile app for user with an analytics dashboard for business. I currently have two APIs:
The main API, to manage user resources.
The business API to query analytics about the users resources.
My problem is that I'm trying to create a single Authentification API. I want the login logic to be independent from other two API's. The flow that I see is:
User or business log in -> LOGIN API -> Generate Token with claim of AccountType.
I'd like to also have three separate DbContext with the two others linked to CredentialsDBContext
public class User {
public Credentials Credentials {get; set;} // CredentialsDBContext
public Shirts Shirts {get; set;} // MainDbContext
}
How can I do this, knowing that you can't create have two DBContext in a single class?
happily you are not the first one who wants to this! actually this is the approach most of the server-side apps take.
There is a protocol called OAuth2.0 with OpenId Connect which help you to completely separate user authentication/authorization from your business logic.
There are popular libraries that do this job for you like :
IdentityServer4
OpenIddict
and much more
Also it worth to note that you can have multiple DbContexts in your project and they can also point to the same database, but that way it may be hard to create the database using Code First approach and you may need to create it manually.

Can we restrict users in identity server4 to specific applications?

I am trying to implement IdentityServer 4 for enterprise scenario.
I understand that users are registered against Identity server.
My question is how to give permissions to users against applications, like as users are needed to assign to a particular application, if not assigned application should return unauthorized.
If a user needs to access multiple applications then multiple assignments are needed.
I am looking a way for Identity server to invalidate the submitted token if the user doesn't have access to the application in a single go, even though the challenged token might be valid if it is submitted by other application which the user has access to
Identity Server absolutely handles authorizations on the most basic level. It creates authorization codes and access_tokens that are essential in an applications authorization. Without them you cannot get authorized. Thus for others to claim Identity Server does not do authorizations is flat out wrong.
I came in here a week ago looking for a solution for this very same problem. I want to restrict users to specific applications by not granting them access tokens if they fail to meet certain parameters, in my case a UserClient table. Lucky for you I have a solution. Identity Server 4 implements a few, what they call, CustomValidators that occur at the time of authorization or token creation. They are
internal class DefaultCustomAuthorizeRequestValidator : ICustomAuthorizeRequestValidator
internal class DefaultCustomTokenRequestValidator : ICustomTokenRequestValidator
public class DefaultCustomTokenValidator : ICustomTokenValidator
There name really says it when they get called. Each one contains a single method
public Task ValidateAsync(CustomAuthorizeRequestValidationContext context)
{
return Task.CompletedTask;
}
Notice something? That's is right! It does nothing. Almost as if they are meant to be replaced. (It is).
This is the area that you can add your custom logic to reject the request. CustomAuthorizeRequestValidationContext contains ClientId and User claim information. It also contains a boolean value called IsError. Simply set that to true and whamy! Access denied. You can also set error messages etc. Here is an example that implements the ICustomAuthorizeRequestValidator inface that will restrict a user based on there user Id
public Task ValidateAsync(CustomAuthorizeRequestValidationContext context)
{
var sub = context.Result.ValidatedRequest.Subject.FindFirst("sub");
if (sub != null && sub.Value != "88421113")
{
context.Result.IsError = true;
context.Result.Error = "Unauthorized";
context.Result.ErrorDescription = "You are not authorized for this client";
}
return Task.CompletedTask;
}
Feel free to inject a dbcontext or two to read off of your userclient table. I check the sub claim to be null because this will get hit several times before actual login occurs.
From what I noticed all three behave similar in terms of use, but different in terms of outcome. Setting an error ICustomAuthorizeRequestValidator will prevent the redirect to your client and instead direct you to the Identity Server error screen. The other two will redirect back to the client and generally throw some throw some sort of HttpResponse error. Therefore replacing the ICustomAuthorizeRequestValidator seems to work best.
So simply created a class that implements ICustomAuthorizeRequestValidator. Then add that into your identity services like so
services.AddIdentityServer().AddCustomAuthorizeRequestValidator<MyCustomValidator>()
and you are done done.
You can add a claim in your IdentityServer4's claims table called "role" and in your application, add some UI to authorize a person via email or similar, and then set his/her role in the claims db. And you can also delete the authorized user from your application, which should un-assign a role to that particular person. Thus he/she although is successfully authenticated, can't use your application because you have authorized then. Hope this approach helps you!
For users, IdentityServer is authentication only. Authorization should be handled by your application.
Authentication = Verifying who a user is
Authorization = Verify what a user can do
Update
I wrote an article on this topic to clarify how OAuth 2.0 does is not user-level authorization. Hope it helps! https://www.scottbrady91.com/OAuth/OAuth-is-Not-User-Authorization
As Scott says, Identity Server will authenticate that the user is who they say they are, not explicitly tell you what that user can do.
You can use the claims returned as part of that authentication to then perform authorization checks within your app. For example, you might use the sub or id claims to perform checks from your app on whether the user associated with that sub/id is allowed to access a specific resource.
The water gets a bit muddier when you bring role claims into the picture, but so long as you appreciate the difference between authentication and authorization you should be ok.
In our enterprise scenario we split it into layers:
We introduced a tenant -- a customer (organization) of our enterprise
solution.
Then we have roles (not more than 20 or so) assigned for
each particular user.
IdentityServer fetches users from tenant and access APIs. The only pre-check it performs is that a particular client (application), requested a token, is not restricted for the particular tenant (customer-level licensing), otherwise we display a message and block the challenge response.
Then we come to an app. With a valid token, having tenant and roles inside. The roles-to-functions assignment could be unique within the tenant. So the application itself performs a granulate permissions check, using a separate API. The application is free to enable-disable some functions or even redirect to the special page in IdSrv "Access denied for the app".
With such approach we are scalable, we are configurable, we are as fast as we want. In previous generation we had "all in one" identity+access+licensing monster-like system, and we decided to split. Today we do not face any real limits with adding new customers (tenants), having 20000 users in average each.
Another way, you can redirect user back to respective client login page it they are not assigned to application/client by using IProfileService of IdentityServer4.Services
public async Task IsActiveAsync(IsActiveContext context)
{
if (!string.Equals("MyAllowedApplicationId", context.Client.ClientId, StringComparison.OrdinalIgnoreCase))
{
context.IsActive = false;
}
}
You have to set IsActive = false to redirect user back to login page where user can login with user details which is allowed in application

ASP Net MVC Core - Load User Data From Active Directory when User browses Any Page

Here is my development environment:
Intranet Website
Active Directory Authentication/Authorization
Asp Net Core
I am trying to get the data stored in Active Directory attributes when a user enters firstly to any page in our application. All users rights and permissions, employeeid, studentid, etc.... are stored in AD Attributes and Security Groups. Some Attributes need to be displayed on the website too.
Let's say my website got the following urls...
http://mysite/Home/Index
http://mysite/Student/Index
http://mysite/Student/MyJobs
http://mysite/Staff/Applications
etc....
Any users can go onto some areas/urls of the website freely from other Intranet portals and I don't know where should I write the code to fulfill that criteria. The problem is that, there is no specific entry point to the application like http://mysite/Login or Authenticate, etc. If there is, I could load all users details and rights from AD on that single entry point.
In MVC5 era, I used Custom Global Authorize Attribute and put it on the BaseController is inherited from all other controllers to load that AD data. I put the AD's data into Session on the first hit and use the Static Class to display on Views and use in Controllers. But when I did some research in MVC Core, some say that it's outdated and I should use the Authorize Policy instead of custom Authorize Attributes.
Getting the data from Active Directory is already achieved by using my old webservices and we don't need to worry about .Net core not supporting AD yet.
I looked at the tutorials about Policy and saw something about Claims and Custom User Managers. I couldn't decide which one I should use to load data from Active Directory to the object (probably Scoped Object DI) which lasts for the whole user's session.
Should I load the data onto claims attributes
Eg...
var claims = new List<Claim>();
claims.Add(new Claim("UserName", "John.Smith", ClaimValueTypes.String, Issuer));
claims.Add(new Claim("RefNo", "02343001", ClaimValueTypes.String, Issuer));
claims.Add(new Claim("Email", "MyEmail#email.com", ClaimValueTypes.String, Issuer));
Or Should I write customized SignInManager and IdentityUser?
Eg...
public class ApplicationUser : IdentityUser
{
public string RefNo { get; set; }
public string Email { get; set; }
}
Is there anywhere I could put my code to check AD and load data?
And should I store the data in that Claimed Object rather than using Session Data?
Could you guys please advise me? Feel free to criticize if I miss anything and my idea is not working.
You're right in saying there's no System.DirectoryServices yet (it's on the backlog, I promise) so there are a couple of places to do this.
If you're already using Integrated Authentication you have SIDs for group membership, which are resolved when you call IsInRole(), so you can use role based membership (rather than Claims based) to solve basic authentication problems.
However if you want to support a forms based mechanism then you should look at using the cookie middleware, raw, to at least give you a simple login, calling your web service to validate your login. You could query your API in the controller code, and write an identity cookie. This cookie automatically encrypted and signed, so it can't be tampered with.
The problem comes when you want roles, and attributes. If you head down the cookie route you might be tempted to put all of those as claims in the identity before writing the identity out as a cookie. This might work, provided there are not too many - cookies have a maximum size (browser dependent, but under 4k usually). You can used chunked cookies, but there's a performance impact here. Instead you might use a reference cookie, where you put in a reference to another store where the actual fully populated identity is stored, be it session, redis or something else.
Then in the claims transformation middleware you can pull the reference out, go to your store, and rehydrate the identity.
I'd honestly avoid trying to merge all of this into ASP.NET Identity. That's mean to be the sole source for user information in an application, and in your case that's not true. Your sole source should be AD.
There's also a port of Novell's ldap library to core, which should stand in nicely for DirectoryServices should you want to avoid your web services approach.

Implementing Application only API key and secret in servicestack with additional user api keys

So, I'm trying to figure out the best way to implement the following authentication in my ServiceStack api.
I want to secure all API calls such that they are only available to applications we define (so semi-private). These applications would be linked to our Company tables. So, lets say we have one table ApplicationKeys linking to Company.
Additionally, we have Users (also linked to a company). These users can also be given an api key to allow specific user related functionality to the app.
How/what is the best way to implement allowing an application to access the api with these two levels of security. 1) endpoints that only require the application to be authenticated. 2) endpoints that require both application and user to be authenticated.
Additionally, I'd like to be able to use the new JWT authorization once 1 or 2 above is validated.
The first thought (and what i'm still working on) is a custom AuthProvider for 1. I'm using ApiAuthProvider as the example. I have to change the type of auth repo so that it only validates against the company and api key. However, even if this first bit works, I'm not sure how to expand it.
It's going to be problematic to try support multiple API Key Auth providers since the same HTTP bearer token would need to support 2 different API Key providers, one for Company and another for User.
The built-in ApiKeyAuthProvider is for User API's key and allows users to authenticate using one of their API Keys.
The Company API Key is different since it's not tied to any user, my initial thoughts is to implement this as a Request Filter restriction instead of trying to integrate it as an AuthProvider which are tied to Users. So I would likely do something like add a custom X-Company-Key HTTP Header and add a Request Filter Attribute to validate the company key, e.g:
public class ValidateCompanyKeyAttribute : RequestFilterAttribute
{
public override void Execute(IRequest req, IResponse res, object responseDto)
{
var companyKey = req.Headers["X-Company-Key"];
var company = GetValidCopmany(companyKey);
if (company == null)
{
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.EndRequest();
return;
}
req.Items["company"] = company; //if info needed in Services
}
}
Which you can then generate on your Services, e.g:
[ValidateCompanyKey]
public class CompanyServices : Service { ... }
An alternative approach may be to create a special "Company" User as a placeholder to hold all company API Keys and maintain which Company the key is for using one of ApiKey table custom ref data properties. Of course if you're creating your own custom API Key AuthProvider you can add your own explicit fields. The benefit of this approach is that you can use the same Auth Provider to validate both Users and Company API Keys.
To validate Users via an API Key you can just use the existing ApiKeyAuthProvider and ServiceStack's built-in [Authenticate] attribute, e.g:
[Authenticate]
public class UserServices : Service { ... }
Not sure where using JWT's would fit in, a HTTP Request can only contain 1 bearer token and if they're authenticating via API Key they wouldn't be authenticating using a JWT as well. You can of course register both AuthProviders which will allow Users to authenticate using their preference.