Using Openiddict for user identity management and application access - openiddict

I have a .NET Core web API that uses openiddict for identity management that is tied to ASP.NET identity in a SQL server backend. Many applications can leverage this API with a subscription. I have the following requirements.
Only authorized applications can use the API
Each application can optionally use the identity features of the API to manage their application specific users as implemented by Openiddict within the API (currently the authorization, password, and refresh token flows are enabled).
All endpoints should require that an application be in the Oppenidict application table and this application ID should be available on every request due to multi-tenant support in the API.
Endpoints that have an [Authorize] attribute must be have a user that is authenticated via the Openiddict identity model.
To implement requirement (1), would I need to implement a custom authorization function that checks for an application secret or should another flow be enabled in openiddict that takes care of ensuring only authorized applications are allowed access to the API (regardless of authorize attributes)? In this case, a user may not be authenticated, but the application must still have rights to access the non-authorized endpoints of the API.
To implement requirement (2) for external identity providers, is it possible to configure multiple secrets for each application registered within openiddict to allow their users to leverage facebook or twitter for authentication? This is important, because the API would need call AddFacebook() during configuration for each application that can access the API (not the clientID and secret of the API itself). Because multiple applications each have their own facebookID and secret, I would assume this would only work if openiddict could allow the registration of multiple Ids and secrets for the same provider type via AddFacebook() for example.
To implement requirement (3), is there a built in way to get the application ID of the calling application from openiddict like there is if the user was authenticated?

To implement requirement (1), would I need to implement a custom authorization function that checks for an application secret or should another flow be enabled in openiddict that takes care of ensuring only authorized applications are allowed access to the API (regardless of authorize attributes)?
Starting with RC3, client identification was made mandatory by default: if you don't send a client_id corresponding to an entry in the applications table, your request will be rejected by OpenIddict itself. In previous versions, you could opt for this feature by calling options.RequireClientIdentification() (it's now opt-out).
To implement requirement (2) for external identity providers, is it possible to configure multiple secrets for each application registered within openiddict to allow their users to leverage facebook or twitter for authentication? This is important, because the API would need call AddFacebook() during configuration for each application that can access the API (not the clientID and secret of the API itself). Because multiple applications each have their own facebookID and secret, I would assume this would only work if openiddict could allow the registration of multiple Ids and secrets for the same provider type via AddFacebook() for example.
There's no direct relationship between OpenIddict and the authentication schemes you use, so no, you can't configure multiple Facebook credentials "via" OpenIddict as the two are unrelated.
Assuming you need that for multitenancy purposes, you may want to read https://stackoverflow.com/a/49682427/542757 to learn how you can override ASP.NET Core's default options monitor so you can provide tenant-specific options for authentication handlers like OpenIddict, Facebook, Google and anything else.
To implement requirement (3), is there a built in way to get the application ID of the calling application from openiddict like there is if the user was authenticated?
Assuming it's known (i.e you didn't explicitly make client identification optional in the OpenIddict options), yes. E.g from a MVC controller:
var result = await HttpContext.AuthenticateAsync(OpenIddictValidationDefaults.AuthenticationScheme);
Debug.Assert(result.Ticket != null, "The authentication ticket shouldn't be null.");
// The presenters list contains the authorized parties allowed to
// use the access token with your APIs. Usually, it contains a single value.
// Note: this extension requires a using for AspNet.Security.OpenIdConnect.Extensions.
var client = result.Ticket.GetPresenters().FirstOrDefault();

Related

Integration of frontend and resource server using okta authentication and client credentials API authentication

We have an application that has frontend UI(Which is a web application) which communicates with a resource server. Our frontend will be using some APIs from a resource server to get data.
I am planning to add frontend to Okta and provide access to okta registered users.
In the resource server, we have some APIs that we want to expose to our customers to integrate in their system(Programmatically). To use our APIs, we have to provide client credentials(client ID/secret) to them. Using clientId/Secret, they will get access_token and will use that in a subsequent request. We can display this clientId/Secret via frontend UI once the user logs in to it via Okta.
How should I authenticate requests to the resource server from the frontend? And how do I authenticate requests to resource server via customer using clientId/Secret? Should I use one or two different tokens for this purpose?
Does Okta provides per-user client Id/secret that user(customer) can use to get access_token and send it to access resource server and resource server validate token against Okta.
I just did something very similar. You can read about my experience here: How to pass/verify Open ID token between .net core web app and web api?
I don't know what application framework you are using (.net, node, etc), but if you're using .NET the steps are to (a) install the middleware in your web app, (b) install the middleware in your api app, and (c) make sure calls from your web app to the api app pass the id_token.
If you, in addition to that, need to secure it for external users - it should work the same way. The only difference is they will manually call the /authorize endpoint to get their token - but the middleware should take care of the token verification for you in both cases.
Note I did experience one odd thing which is that I needed to pass the id_token and not the access_token. It is also worth mentioning that the claims were interpreted differently in the app and the api (in that the name of the claims for say, userid, were different between them - the data was still the same).
You will have to use 2 different access tokens. There are 2 different flows going on here:
Web UI to API
Business partner system to API
Technically this means:
Authorization Code Flow (PKCE)
Client Credentials Flow
And in terms of tokens it means:
In the first case there is an end user represented in access tokens (the 'sub' claim)
In the second case there is only a Client Id claim in access tokens
I can advise on token validation techniques if needed - let me know.
To me though this feels like an architectural question - in particular around applying authorization after identifying the caller and versioning / upgrades.
Based on my experience I tend to prefer the following architecture these days, based on 2 levels of APIs: eg with these ones exposed to the internet:
User Experience API serves the UI
Partner API deals with B2B
And both entry point APIs call the same core services which are internal. Might be worth discussing with your stakeholders ..

How do I use Google's Identify Platform to authenticate against Cloud Endpoints?

In our organisation we use the Google Kubernetes Engine (GKE) to implement a micro-service architecture. As we are also G-Suite users, everyone in the organisation is guaranteed to have a Google account. In consequence we would like to use those accounts to manage authentication and authorization of micro services.
We have prototyped login using the angularfire2 client to authenticate against the Google Identity Platform. We also have Google Cloud Endpoints configured to control access to relevant services.
The piece we are missing is how to get from the identity in Google to an access token we can use on our services -- the access token coming back using the Firebase API has no claims in it, and the documentation on custom claims seems to make it quite clear that these go into the identity token.
My expectation would be to have JWTs with the appropriate audience (our backend), containing a sufficient set of claims to implement role based access control within the services. Ideally the infrastructure could validate a claim already -- some of our services are small enough to require only one role, which could be enforced outside the service. Or we could annotate our endpoints (Protobuf) with the required claims.
In the GCP environment, what is the standard process of creating access tokens to be used for accessing GKE services? Is there anything that supports this?
The piece we are missing is how to get from the identity in Google to
an access token we can use on our services -- the access token coming
back using the Firebase API has no claims in it, and the documentation
on custom claims seems to make it quite clear that these go into the
identity token.
Google OAuth Access Tokens do not have an identity in the sense that you want to use it. Identity is stored in the Identity Token. Add the scope "email" when authenticating the user. Google will return an ID Token. For some frameworks, you can request custom claims for the Identity Token.
In the GCP environment, what is the standard process of creating
access tokens to be used for accessing GKE services? Is there anything
that supports this?
There are two types of access excluding methods such as API keys. User Accounts and Service Accounts. Service-to-service typically uses service account Access Tokens (RBAC) or service account Identity Tokens (IBAC). In your case, you want to use Identity Platform which means User Accounts.
If I was designing this system, I would use User Accounts to authenticate with the system - Firebase is great for this purpose. I would look up what roles this identity supports/allows from my database (Firestore) and create a service account Access Token with the required scopes for GCP services. I would then use this Access Token for GCP service-to-service authorization. If I also required custom roles for my own services, I would create a custom Identity Token with my custom roles and include that as a custom HTTP header and include the Google Access Token in the standard HTTP "authorization: bearer" header. I would use the service account private key to sign my custom Identity Token or use a GCP IAM API to sign for me so that the other end can verify with the service account's public key. This method prevents data leakage at the client, no private keys are distributed, scopes/roles are not disclosed, etc.
I would suggest you follow this doc of authentication between services by using service account files.

Web api 2 security - key for api

I'm building an API that my public mobile app (xamarin forms) will call to get information. However to delimit the users of the API to just my app for security reasons, I want the public mobile app (xamarin forms) to pass a key to be able to call the API. Is basic authentication the best option then ? Or is there another approach ?
You can use any Auth based mechanism in your web api project. The best would be the latest Identity 2.0 using Owin.
OAuth is an open standard for authentication, and enables a resource
owner to notify a resource provider that permission should be granted
to a third party in order to access their information without sharing
the resource owners identity.
In your Xamarin client project (mobile app) use the Xamarin.Auth SDK to authenticate your users. It provides many features and also helps you to scale and use Social authentication as well.
Xamarin.Auth is a cross-platform API for authenticating users and
storing their accounts. It includes OAuth authenticators that provide
support for consuming identity providers such as Google, Microsoft,
Facebook, and Twitter.
The authentication flow when consuming an OAuth identity provider is as follows:
The application redirects a browser to an identity provider URL. The
URL query parameters indicate the type of access being requested.
The identity provider handles user authentication, and returns an
authorization code to the application.
The application exchanges the authorization code, client ID, and
client secret for an access token from the identity provider.
The application uses the access token to access APIs on the identity
provider, such as requesting basic user data.
The application uses the OAuth2Authenticator and OAuth2Request classes, provided by Xamarin.Auth, to implement the application side of the authentication flow.
The detailed explanation of Authenticating Users with an Identity Provider
Using the Xamarin.Auth component for authentication implementing is available here.

Adding additional claims to a token after authentication for additional services

Imagine a scenario where a desktop application calls a Single Sign On service to log the current user in. This service authenticates the user and returns a token (a Json Web Token) which is signed with the private part of a public/private key pair. This token has some claims about the identity of the user.
The application then wishes to call a different service for some data and so passes on the token to the service. The service uses the claims in the token (and the fact that it was signed by the SSO service) to identify the current user and to determine which data to return. So far so good.
Now say the application wants to provide some additional pieces of information which are not related to the identity of the user but some context about the current session the user is using in the application (like the current database they are connected to).
These seem like good candidates for additional claims which can be sent with the request, so the data service can extract the claims from the token and use both the identity claims from the SSO and the application specific claims from the desktop application to decide what to do and how to do it. (like which database to update)
The issue is that we can't add claims to the existing token as this has been signed by the SSO service and the application can't know the private key to sign the new token. If the original token is not present then the data service can't trust that the identity came from the SSO, so can't allow access to the data at all.
Options I can think of:
After authentication the application calls the SSO service again providing a collection of claims (secured in some way, not just anyone can call the SSO to get additional claims added to the token) and the SSO token, and the SSO service returns a new token which contains the identity claims and the additional claims the application wants to add
The application creates a new token which it signs and one of the claims in this token is to original token the SSO service provided.
Both of these have pros and cons, but on balance I think I prefer the first option.
To complicate things a little more, there is not just one 'application' there are a few. All will use the same SSO service, and all will want to add some additional application specific claims (ie the claims for app1 and app2 will be different)
Is there an out of the box solution for this problem already? Or are there other ways of dealing with this issue then the options outlined above?
Not sure I like either option.
After authentication the application calls the SSO service again
providing a collection of claims and the SSO token, and the SSO
service returns a new token which contains the identity claims and the
additional claims the application wants to add
I don't think any SSO service will allow you to do this. The claims in the token are signed as the SSO service guarantees they are correct. If the SSO service would start signing arbitrary data, that guarantee no longer holds.
The application creates a new token which it signs and one of the
claims in this token is to original token the SSO service provided.
If you let your application sign access tokens, you'll have to distribute the public keys of both the SSO service and the application. And your data service now has to trust both.
Why not just pass this extra info the data service may need as parameters in the service call? If you are calling the service over HTTPS, the integrity of whatever you pass is guaranteed.

Multiple Authentication / Authorization support for Web API via OWIN

I have a Web API project of ours that needs to be secured. I am planning to allow the user's that registered with my app to use the API [Forms Authentication], users with their own organizational accounts [ADFS] and Social Sign-In.
I have all the middleware available to plug-in and make available to the user's. However, in my application I do have custom roles and privileges that are to be provided so that my application authorizes the service calls based on the existing privileges. What is the best way to accomplish this.
I think that I will be required to provide my own custom implementation of the UserStore and UserManager with my own IUser Implementation.
Kindly suggest the best practice for this scenario.
With multiple authentication middleware registered, you can get multiple claimidentity's.
register each type of authentication you want to support.
I would be sure to add a claims transformation module at the end of the pipeline. Thinktecture has an example. ThinkTecture Owin Claims Transformer
This would give you one place to look up and add all the application type claims for an authenticated user in one spot.
Simple pseudo example (geared to webapi, but concept the same). Authenticate with bearer or basic or both then transform.
//identity 2.0 user manager stuff used in your modules
app.CreatePerOwinContext(ApplicationSession.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Token Authentication -> get a principle
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
// Basic Authentication. -> get a principle
app.UseBasicAuthentication(app.CreateLogger<BasicAuthenticationMiddleware>(),
"Realm", ValidateUser);
// transform claims to application identity. Add additional claims if needed
app.UseClaimsTransformation(TransformClaims);
It sounds like you are looking for externalized authorization. Externalized authorization is the act of:
decoupling business logic from authorization logic
expressing authorization logic as centrally managed, centralized authorization policies
protecting your APIs through a common layer
enabling fine-grained & dynamic access control through the use of attribute-based access control (ABAC) which extends what's possible with RBAC (role-based access control).
Have a look at XACML, the eXtensible Access Control Markup Language. You can find some more information on OASIS's website.
Also check out NIST's project on ABAC.
Once you defined your authorization logic, you can decide how to enforce it. This can be done either via direct enforcement at the entry of your apps or can be done in a provisioning way whereby the permissions derived from the authorization policies are fed into an authentication token e.g. SAML as attribute assignments.
HTH
This is what I ended up designing for a system with similar requirements. The key is to separate the authentication and authorization logic.
Build Owin authentication middleware components that take care of establishing user identity based on various login methods you mentioned. Looks like you have this accomplished. Set ASP.NET identity based on the user.
Retrieve the roles/permissions for the logged in user from your store. This can be done as a separate Owin middleware or a part of your authentication. Add the permissions as Claims to your Principal.
Extend your roles/permissions store to map API service operations to the application permissions.
Implement a custom API Authorize attribute and apply it to every API operation. In this attribute you will have access to the operation name and the user Claims (permissions). Match the Claims with the permissions you mapped in the step above. If there is a match, return IsAuthorized=true, otherwise, return false.
Here is a similar issue at a simpler level.
How do you setup mixed authorizations for different authentications in .net (web api 2 + owin)