Transformation of token received from OpenID server - asp.net-web-api

I currently have a distributed system containing an OpenID Connect server (IdentityServer3) acting as SSO server. The clients using the SSO server are AngularJS SPA:s with WebAPI v2 backends.
I got the basic login flow working, but I need some help with configuring the WebAPI/OWIN pipeline to allow transformation of the received token claims, ie. removing unnessecary claims and adding local claims. I'm assuming I need to create a local JWT instead of using the JWT received from the SSO server.
The question is, what is the best way of doing this? Are there OWIN middlewares that can help with this, or do I need to "manually" generate a new locally signed JWT from the claims received from the SSO server?
Current implementation details:
The AngularJS SPA authenticates against the SSO server using
authorization code flow and receives the authorization code.
The SPA posts the authorization code to the WebAPI.
WebAPI receives the authorization code and requests an AccessToken/JWT from the SSO server using the OAuth2Client class (part of Thinktecture.IdentityModel.Clients). This AccessToken is returned to the SPA to use in any further requests done to the WebAPI.
So my question mostly relates to step 3. How do I best change my current flow to generate a token also containing the local claims?
Also, what kind of authentication middleware should be used with your proposed solution (JwtBearerAuthentication, OpenIdConnectAuthentication or OAuthBearerAuthentication)?
Apoligizes for my probably confused terminology usage, I'm a beginner regarding OAuth and especially the OWIN pipeline. :)

Your WebApi should use BearerTokenAuthentication.
To get access token (access_token) and claims (id_token) in single call you need to set response type as ResponseType="token id_token"
You can checkout various ready to run sample at IdentityServer3 Samples. Specifically checkout implicit flow sample.

Related

Spring boot API with both Oauth 2.0/OpenID Connect and internal authentication?

I'm having a hard time figuring a good way to implement Oauth 2.0 and OpenID Connect authentication alongside an existing internal email+password authentication for a B2B Web app's API using Spring security.
We have a backend REST API that is a Spring Boot servlet application which currently authenticates users with OAuth 1.0 and the password grant. The front-end is an Angular single-page app through which users must log in with their username and password. The API's /oauth/token endpoint then delivers an opaque access token to be used for fetching secured resources that are then displayed within the app.
We'd like to add the possibility to log in using external authentication with OpenID connect, which is a perfect opportunity for switching to OAuth 2.0 and JWT tokens. Our API would then accept JWT tokens it delivered as well as external JWT tokens emitted by accepted issuers.
Reading and validating JWT tokens won't be a problem using Spring security's OAuth Resource Server. However things get complicated with how to make the classic username+password login flow work with JWT tokens.
We thought about delivering JWT access tokens the same way we used to with our old OAuth 1.0 tokens. The thing is, newer OAuth specifications advise against using the password grant, plus it simply isn't supported in the Spring authorization server project we're planning to use. The authorization-code flow w/ PKCE seems like too much for this case as we do not want the back-end API to render a login form but use credentials entered in the existing login form that is part of the single-page app.
I've read a lot about not using OAuth for 1st party login since its primary use is for external authentication, but again, that doesn't apply since we also want 3rd party authentication.
What would be a secure way to implement a Spring boot authorization server that can deliver JWT access tokens to a 1st party client in exchange for a user's credentials, all this using the existing log in page, and given the password grant type no longer being supported?
I thought about implementing a preliminary step that would be a POST request with Basic authentication to a /login endpoint that just returns a 200 HTTP status, then proceeding to the /oauth2/authorize request that would deliver the authorization code immediately without redirecting since my session is authenticated.
I'll be happy to provide more details if needed. Here are the resources I'm using for this project.
What about setting up an authorization-server capable of identity federation?
In such configuration, the authorization-server is responsible for providing with identities, proxying one or more sources (your existing user database for instance, plus maybe Google, Facebook, Github, etc.)
Keycloak does it for instance.
From the client point of view (your Angular app), the authorization-server is used to get:
access-token: put in Authorization header of requests to secured resource-server(s) (can be a JWT or an opaque string, doesn't matter, clients should not try to extract data from access-tokens)
refresh-token: send to authorization-server to renew access-token before it expires
id-token: get user-profile data (email, username, profile picture, etc.)
You should have a look at https://github.com/damienbod/angular-auth-oidc-client for connecting an Angular app to an OIDC authorization-server.
From resource-server point of view, access-tokens are the source ofr setting-up security-context, either by decoding and validating a JWT locally or with token introspection on authorization-server.
Have a look at those tutorials for such resource-servers configuration.

How implement a basic IAM oauth2 flow with spring security?

I am currently developing using spring security oauth2.
Currently, the frontend is SPA, and it is developed as react that operates with client side redering.
My rest api has the spring security starters libraries. But I don't know how to use oauth2 flow provided by spring.
So my question is: Can I use spring security as IAM to protect my web and api?
Does spring security have the known oauth2 grants and how use them ?
Implicit grant
Client Credentials Grant
Password grant
Don't use implicit grant
It is not recommended to use the implicit flow (and some servers prohibit this flow entirely) due to the inherent risks of returning access tokens in an HTTP redirect without any confirmation that it has been received by the client.
source: https://oauth.net/2/grant-types/implicit/
With implicit grant, access token is returned immediately without an extra authorization code exchange step. This extra step is usually performed in your backend.
Web > token > Api
SPA frontend and its Rest Api is a very common approach, used since simple startups until big companies. The flow summarized is:
Your users will start the web application.
As they were not signed in before, you web app will show them a login screen (a page provided by the authorization server).
After authenticating, a consent form is showed to the user.
After user consent, the authorization server will send you an authorization code.
The web app will exchange this code for a token.
After getting back this token, the web app store it in the client(browser) and send it as a header when apis needs to be consumed.
Your private rest apis must validate if token of the web app (header) is valid by sending it to one endpoint of the authorization server
If token is valid, your api rest is allowed to respond to the web client. For instance a json with products, employes, some update of customer order details, etc
For this flow to work, you will need:
web spa with a hint of backend. Backend is required because you cannot have a proper user session in static solutions like apache or nginx.
authentication and authorization server: Known as identity and access management (IAM) or some third app which provide you the basic oauth2 endpoints to manage a proper security for your apps.
your apis: foo-api , bar-api, baz-api, etc
spring security
In the minimal scenario in which:
you will have only one web + one rest api, and nothing more in the future (mobiles, iot, etc)
you don't have an authentication/authorization server
you have a mix of functional apis (employee, products, etc) and its security (spring-security) in just one artifact
you don't need user session in your web
you don't need a logout feature
Flow could be reduced to:
Your users will start the web application.
As they were not signed in before, you web app will show them a login screen (a page provided by spring-security).
After authenticating, a consent form is showed to the user.
After user consent, the authorization server will send you an authorization code.
The web app will exchange this code for a token. Since your api is using Spring security, the token generation is covered.
After getting back this token, the web app store it in the client(browser) and send it as a header when apis needs to be consumed.
Your private rest apis must validate if token of the web app (header) is valid by sending it to one endpoint of the authorization server I think the spring security chain filters handle this.
If token is valid, your api rest is allowed to respond to the web client. For instance a json with products, employes, some update of customer order details, etc
Here some samples of token generation and protected endpoints with spring security. I will try to upload a ready to use sample:
https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/
IAM
If you will have more applications and complex scenarios in the future, I advice you to choose some open-source iam like:
Glewlwyd,Keycloak,OAuth.io,ORY Hydra,SimpleLogin,SSQ signon,
Commercial services like:
Auth0,Curity Identity Server,FusionAuth,Okta,Red Hat Single Sign-On,cidaas.
Or try to develop a new one using pure spring-security
Lectures
Some recommended answers with more oauth2 details:
https://stackoverflow.com/a/62123945/3957754
https://stackoverflow.com/a/62049409/3957754
https://stackoverflow.com/a/57351168/3957754
https://stackoverflow.com/a/63093136/3957754
https://stackoverflow.com/a/54621986/3957754
https://stackoverflow.com/a/63211493/3957754

Integrate SAML authentication for APIs developed in microservices

I need to develop set of microservices (rest APIs) which is to be used by web and mobile client, the microservices are sitting behind API gateway, I've to integrate with SSO (using SAML) for user's authentication, I understand that SAML token to oAuth2 token conversion has to be done so that I can verify auth token at API gateway and handle authorization there itself, but the piece which is not clear to me is that who will take care of conversion of SAML token to oAuth2 token, is it IDP who provide this functionality out of box or do I need to built up something of my own?
One possible solution which I'm thinking of is
User (from web/mobile) sign in via SSO
Gets SAML response from IDP
Send that SAML response to server to generate Auth Token
Server gets request to generate auth token, looks for SAML response and validate it against IDP
If SAML response is valid then generate auth token and send it back to client
On subsequent API request from client the token is passed as header which API gateway validates
The thing is I'm bit reluctant to implement SAML and oAuth thingy myself and looking for some ready made solution but couldn't find any, can someone please suggest of any library solving this problem, thanks in advance.
It feels like your approach is correct - it is the role of the Authorization Server (AS) to deal with SAML login integration for you. Only configuration changes should be needed, though of course you need to use an AS that supports SAML integration.
Your UIs and APIs will not need to know anything about SAML and will just use OAuth tokens. There should be zero code changes needed.
Most companies use an off the shelf AS - eg from a low cost cloud provider. My Federated Logins Blog Post summarises the process of integrating an IDP. The walkthrough uses AWS Cognito as the AS - and the IDP could be a SAML one.
I maintain a microservice that sounds like it could help you - https://github.com/enterprise-oss/osso
Osso handles SAML configuration against a handful of IDP providers, normalizes payloads, and makes user resources available to you in an oauth 2.0 authorization code grant flow.
Osso mainly acts as an authentication server though - we don't currently have a way for your API gateway to verify an access token is (still) valid, but that would be pretty trivial for us to add, we'd be happy to consider it.

Securing web app and api using OpenID Connect

I don't want to roll my own security anymore and am looking at using OpenID Connect with my c# API and AngularJS app. I can get all that to work just fine. However, my brain cannot seem to understand how to secure my API correctly for both use cases:
Use Case 1: AngularJS SPA
My AngularJS app connects to my API and sends a bearer token identifying the user and includes user claims. This one is easy and there is tons of documentation on it.
Use Case 2: API to API
Some customers want to access my API directly instead of going through my AngularJS app. In this case, I thought I could use a Client ID/Secret for toen-based authentication which is great except then I know nothing about the user that's using the client id/secret. There could be 10 users using the same custom API that is calling my API. How do I get user info via the API call? I've seen others use API keys that they then lookup the user and create a JWT but I thought there might be an easier way. Any ideas?
The whole point of API to API authentication is that there is no user context. Or well, the user in that case is the machine trying to access your API. You would then need to design your authorization logic around that and implement scope based permissions. Alternatively, your options are to use api keys as you mentioned or if you want OAuth protocol with user context in the api to api scenario - then ResourceOwnerCredentials flow is an option.
API to API communcation
You can use Client Credentials Grant defined through OAuth 2.0. This won't require you to have end user credentials. Now this won't be OpenID Connect. OpenID Connect require the involvement of an end user and bound to authentication. OAuth 2.0 on the other hand is about authorization, checking whether the entity can access the resource.
With Client Credential Grant, your identity server will issue tokens for a specific client. So one of your API becomes the client (resource consumer). From request handling API endpoint, you can accept valid tokens and respond back with resource.
If you require fine grained access control from request handling API, you will require to use token introspection to identify to whom this token was issued. In this case, it will be identification of specific client identity and execute a logic on top of it. You can check the token introspection response to identify such details.
Alternatively, access tokens can be come in form of a JWT. If this is the case, they can be considered as self contained tokens so validation is straightforward.

Simple Web Token (SWT) Authentication in Web Api 2 OData endpoint

Ok, the situation is this.
We already have an existing ASP.NET MVC 5 site with Custom Forms Authentication, Logon, Registration etc with a custom database for roles and profiles already implemented.
We now are adding some new functionality to the MVC site and we decided to use Web Api 2 OData 3 endpoint which lives in another domain. The Web Api currently doesn't include any authentication but we need to be able to map the requests to a certain user to get his roles etc from the backend. The MVC and API sites use the same backend.
What we would like to accomplish is, that when the user logs on in the MVC site, the MVC site calls the Web Api server-to-server with the user's credentials and receives a token that the client can then use to call the web service with.
When API receives a request with the token, it can then map the request with the user in backend and do authorization.
As far as I understand it, Simple Web Token (SWT) could pull it through. But considering the environment, .NET 4.5.1 / Web Api 2 / OData 3 with Entity Framework in Azure Web Role, I started thinking is this SWT something I should really use or if there is any NEW technologies recently published that could easily pull this through. I don't want to add any unnecessary 3rd party dependencies to the project if the .NET stack already contains something like it.
So, what would be the simplest way of pulling this kind of authentication through without adding unnecessary dependencier to the project.
The solution we are looking for, is only temporary meanwhile we redesign our authentication scheme. So we are looking for something really simple to implement that works with least dependencies that need to be removed later on.
I'm using this in a project I'm currently working on. I use the OAuth 2.0 OWIN Middleware component that ships with Web API 2.0 (if you add a new Web API project with Authentication enabled, it includes the base infrastructure).
You would use the Resource Owner Password Flow as defined in the OAuth 2.0 specification. Basically you request a Token from the Web API OWIN Middleware sending:
client_id - identifies your MVC endpoint
client_secret - identifier your MVC endpoint
username
password
And in response you get a bearer token. The token generating is based upon a claims principal, the OAuth middleware component has predefined hooks for adding claims. This token now needs to be added as authorisation header to each response. On the MVC side you might add this to session so that it's always available to make backend API calls in the context of the user associated with an incoming HTTP request. If you're using WCF Data Services Client, you'll need an authorisation service/manager or similar that you can hook into OnRequestSending and OnResponseReceived events, so that you can insert that bearer token into the HTTP headers.
You can customise the OAuth Middleware component as you need to quite easily, it took a bit of time to figure it out as it's not too well documented, but downloading the Katana source code did help a bit as the source code does have some good documentation.
The nice thing about it all is that you simply need to enable HostAuthenticationFilter and add Authorize attributes on the Web API side and it's ready to go. You can get access to the claims principal object and use claims as identifying pieces of information for your user - e.g. identity, roles, other attributes etc.
To get started, look at http://www.asp.net/vnext/overview/authentication/individual-accounts-in-aspnet-web-api
Also as a wrap, I did consider the use of JSON Web Tokens (JWTs) as there is an OWIN library available for generating and parsing these. The use case here would be that you authenticate, get a JWT back, and then use the JWT to get an OAuth 2.0 bearer token. The JWT is useful if you want to move authentication elsewhere, or if you want to get additional information about the user at the MVC side of things.

Resources