How can I integrate with a third-party API secured with oAuth2 in asp.net core 3.1? - rest

We're trying to integrate with an external third-party REST-API that's secured with oAuth2 but the service isn't really an identity provider, so I'm not sure what terminology I'm looking for. Obviously when it comes to looking at "asp.net core" and "oauth", millions of hits come up related to adding it as an identity provider but I don't think that's what we want.
This is how I would expect it to work, based on what I've seen in other saas apps:
User logs into the site
User looks at some "third-party integrations" page and clicks to add this one
User's browser is directed to the other service to login
On successful login, user is directed back and we have access to the bearer + refresh token which we store(?) and use.
Some use of this API is in response to user action (refresh to get results), but some is also just background work so I assume we're storing this information and using implicit flow to refresh the token for as long as we can unless it's revoked.
What asp.net core terminology am I looking for, how would someone properly describe this flow in oAuth terms? We're getting confused between authorization, authentication, providers, handlers, middleware, etc.
In terms of this third-party API oauth flow, in case people want to know, here's what's required:
We call a specific endpoint that tells us the correct authorization and token endpoints
We then redirect to the authorization endpoint, which presents the user with the remote service's login page.
The user logs into the other service and is redirected back and the code and grant_type=authorization_code are provided via the url
We call the token endpoint with that information to get the final bearer+refresh token

Related

How to perform user registration and authentication between a single page application and a REST API with OpenID Connect

Consider that we have:
An SPA or a statically generated JAMStack website.
A REST API.
The website is being served with nignx that also reverse proxies to our API.
--
It is required that a user should be able to register/authenticate with an identity provider (say, Google) through the OpenID Connect protocol. For the sake of simplicity, let us assume that the user has already registered with our API.
Talking about authentication using OIDC, from what I have read on the subject, the steps you take are the following:
Register the application with the IdP and receive a client id and a secret.
When the user initiates a login (with Google) request on the API ('/api/loginWithGoogle') the API sets a state variable on the request session (to prevent CSRF) and redirects the user-agent to the IdP's login page.
At this page, the user enters their credentials and if they are correct, the IdP redirects the user to the callback URL on the API callback (/api/callback).
The request received on the callback has the state parameter (which we should verify with the one we set on the session previously) and a code parameter. We exchange the code for the identity token with the authorization server/IdP (we also receive access/refresh tokens from the auth server, which we discard for now because we do not want to access any APIs on the behalf of the user).
The identity token is parsed to verify user identity against our database (maybe an email).
Assume that the identity is verified.
-- The next part is what's giving me trouble --
The documentation that I have read advises that from here we redirect the user to a URL (e.g. the profile page)and start a login session between the user agent and the API. This is fine for this specific architecture (with both the SPA/static-site being hosted on the same domain).
But how does it scale?
Say I want to move from a session based flow to a JWT based flow (for authenticating to my API).
What if a mobile application comes into the picture? How can it leverage a similar SSO functionality from my API?
NOTE: I have read a little on the PKCE mechanism for SPAs (I assume it works for JAMStack as well) and native mobile apps, but from what I gather, it is an authorization mechanism that assumes that there is no back-end in place. I can not reconcile PKCE in an authentication context when an API is involved.
Usually this is done via the following components. By separating these concerns you can ensure that flows work well for all of your apps and APIs.
BACKEND FOR FRONTEND
This is a utility API to keep tokens for the SPA out of the browser and to supply the client secret to the token service.
WEB HOST
This serves unsecured static content for the SPA. It is possible to use the BFF to do this, though a separated component allows you to serve content via a content delivery network, which some companies prefer.
TOKEN SERVICE
This does the issuing of tokens for your apps and APIs. You could use Google initially, though a more complete solution is to use your own Authorization Server (AS). This is because you will not be able to control the contents of Google access tokens when authorizating in your own APIs.
SPA CLIENT
This interacts with the Backend for Frontend during OAuth and API calls. Cookies are sent from the browser and the backend forwards tokens to APIs.
MOBILE CLIENT
This interacts with the token service and uses tokens to call APIs directly, without using a Backend for Frontend.
BUSINESS APIs
These only ever receive JWT access tokens and do not deal with any cookie concerns. APIs can be hosted in any domain.
SCALING
In order for cookies to work properly, a separate instance of the Backend for Frontend must be deployed for each SPA, where each instance runs on the same parent domain as the SPA's web origin.
UPDATE - AS REQUESTED
The backend for frontend can be either a traditional web backend or an API. In the latter case CORS is used.
See this code example for an API driven approach. Any Authorization Server can be used as the token service. Following the tutorial may help you to see how the components fit together. SPA security is a difficult topic though.

What is the correct workflow for auth to a web site which uses a REST api

I have a web site written in Angular that uses a REST api in order to provide functionality.
I would like to know the proper workflow for authentication to the website.
Let's go back to 1999 - I write a website and all the logic is in the web code. There is no REST API. If someone wants to log in to the website they enter their email and password and I store a cookie on their machine and they now have a 'logged-in' session on my website. By having this cookie they are authorized to do certain things such as write a comment.
All good.
Fast-forward to my new website. This website is written in Angular and all content is provided via a REST API. Some of the REST calls just display data like a bunch of comments. Any anonymous user can make these calls just by browsing the page. However, there the user can log in to the website using their email and password. Again, I store a cookie on the user's machine and they are logged in to the website. Now, because they are logged in to the website they can post comments. These posts are done via a REST API call. However, Google and the Interweb have told me that my REST API should be stateless and i should be using oauth2 for this request.
My question is, what is the workflow for this very common auth pattern?
I thought maybe something like:
User logs in with username and password
One request is sent to my web auth server and a session cookie is created
A second request is sent to my api auth server which issues a valid token for further requests
The two systems are quite separate and do not depend on each other.
If i was to add social login to the mix then (2) above would just be authentication to the required social auth server and (3) would be unchanged.
Yes, your REST API should be stateless.
This is a typical workflow for authentication for a REST API.
User logs in with username and password.
A JSON web token is issued upon login from the backend and sent to the browser.
The JWT(JSON web token) can be stored in a cookie in the Web Storage(local/Session Storage) on the browser.
Subsequent requests to the REST API will have the token embedded in the header or query string for authorization. With that form of authorization, your REST API understands who is making the request and what kind of resource to return based on the level of authorization
A practical example of this can be found in this blog post. Angular 2 was used for the sample app implementation.
I hope this helps!

OAuth Security with Pre-Configured Authorization

I have a scenario where a user has logged into to a web application (authenticated with OpenID Connect) and then needs to access data from a separate REST service.
The REST service needs to determine whether or not the user has permission to access the requested data, but if the user does have permission, then it should grant authorization to the web application without requiring the user to interact with the UI.
Essentially, what I need is a two-legged OAuth solution where the client/relying party is fully trusted but the user, who's already been authenticated, is not.
Going in, I assumed that OAuth could accommodate these requirements, but none of the grant types seem to match the requirements:
Authorization Code is the opposite of what I need, as the user is pretty much automatically trusted but the client is not, requiring that the user grant access to the client via a web form.
Client Credentials trusts the client (which is what I need) but does not give the service an opportunity to determine if the user has permission to the resource (user auth tokens are not passed to the service, making all requests essentially "anonymous").
ROPC (Resource Owner Password Credentials) would appear to be the only option, but requires the web application to know and possibly store the users' login credentials (which is untenable).
Is this a gap in OAuth? Or am I misunderstanding these grant types? If OAuth can't support this scenario, is there another widely adopted open standard that I've missed?
Of note: I only own/control the web application, while the customers (all of which are businesses) own/control both the authentication servers and the REST services. Therefore, a shared, non-proprietary standard is necessary so that our customers will know how to configure their services (IBM, Microsoft, whatever) and so that I'll know how to pass along any authentication tokens, etc.
I think this is possible using normal OAuth2 flows. You have your web application use the code authorization grant to get a token to call the API on behalf of the user.
Your web application makes the call to the API attaching the JWT token in the Authorization header. If the REST service determines the user does not have permission to access the resource, it returns a 401 Unauthorized HTTP response code.
Your web application handles the 401 response by going back to the authorization server and using the client credentials grant to get an access token to call the REST API on behalf of the client itself.
As both grants allow you to get a refresh token, you should be able to switch between access tokens easily.
If there is no trust relationship between the web application and the REST service, there's no way around using the Authorization Code grant since the user needs to be involved anyhow to allow the web application to make the call on behalf of the user.
If there is a trust relationship between web application and REST service you should be able to use the regular OpenID Connect flow to get an access token to the web application at login time that can also be used in calls towards the REST service.
You may pass on the user information as part of a JWT (i.e. a structured) access token that is signed by the web application itself or the OP; that would be OAuth 2.0 compliant. See https://www.rfc-editor.org/rfc/rfc6749#section-1.4 and May an OAuth 2.0 access token be a JWT?.

OAuth access token for internal calls

I'm currently tyring to build an API driven symfony2 web applicaiton.Just a basic application to learn symfony2 and REST.
It would be based on a RESTful api. Calls to the API will be authenticated using OAuth.
For e.g.:
if a client application wants to get data (information about all the fruits) through API it will need to make a GET request to the url and pass the access token as a parameter.So the url will look something like this.
http://www.mysite.com/api/fruits.json?=<access token>
Now the problem is that i would be needing the same data in one of my actions as well.
I need some help here.In order to get get data from above url in one of my actions i will also need to send an access token in the url.
How do i get this access token??
Should there be a fixed token which will be used for all such calls within my application??
You basic application project will grow manifold if you try to do what you want here.
Basically, you need to implement an Authentication Server for this.
i) First, the app should be registered for a scope;
ii) Using the app the user logs in to the authentication/authorization server.
iii) The server verifies if the app has access to the scope and if the user is registered in your system.
iv) Server creates an access token (which is a HMAC signed string) and returns to your app.
v) The app then hits the endpoint (restful API) with the token.
vi) The RESTful service then internally sends the token to the server and fetches the customerID for which the call is made and performs the actions that it's supposed to.
I wrote an answer once on how to create a OAuth Service/Provider - How would an efficient OAuth2.0 server / provider work?
Also, OAuth was designed such that client apps/3rd party software can access a user's resources on his behalf. A very simple example is = An app posting something on your facebook wall on your behalf. It is actually accessing a resource that you own (the wall) and posting to it. You do not need OAuth just to get some data - there are other ways to secure the API.

REST API and client on same server, need API authentication?

First, let me describe the application: we are working on a web-based software which is some kind of custom help desk application. It requires the user to login (we use FOSUserBundle). After login the user is redirected to the dashboard. From the dashboard there is no more page reload, the frontend is build on Angularjs and the user can get anywhere within the application without page reload. You could speak of a single page application.
So the data that is presented to the user, is fetched from a rest api (we use FOSRestBundle). This works quite well at this point.
There is some kind of dilemma. Only our staff will access this application (for now). So a staff member needs to login to access the helpdesk. The data that is pushed to the frontend via angularjs is called via api, so the user that has just logged in needs to authenticate again on every request because of rest.
Problem: Since the backend runs on symfony2 let us just try to get the user object of the currently logged in user when an api call is made:
$this->get('security.context')->getToken()->getUser()
returns anon. that stands for anonymous, or
$this->getUser();
returns just null.
So the authenticated context seems to be gone when using the rest api. However when I call an action directly without rest, I can get user information.
So what we need is to secure our rest api and get user information on every api call. We don't want third party people to access our application, just staff. I am not familar with OAuth, but the user will be redirected to a third party page to Allow/Deny access to his data? This would not be an option for us.
Based on that information, do you have any suggestions or ideas how to secure the api and transport the user data so that getUser does not return null or anon. but the actuall logged in user?
there's another way to resolve your problem.
It's by using Certificates.
you can generate certificates then use Http tunneling (https obviousley), the server will ask for a certificate (you've to configure Apache for that but it's not a big challenge).
with this in place, you've to add a CertificateManageron the server side to ensure that the certificate is valid and to know who's calling the service (to be able to authenticate the user at each request), the CertificateManager(or what ever you'll call it) will probably have to be configured within you filters chaine (as known in the java world), et voilĂ 
Hop that help you,
Abderrazak
REST is stateless so you will have to send some kind of authentication/authorization in each request. You can use HTTP BASIC AUTH or something like OAuth.
Have a look at https://github.com/FriendsOfSymfony/FOSOAuthServerBundle
I'm kind of building our application in exactly the same architecture (RESTful API with Symfony2 back-end and AngularJS frontend.
Another way is to duplicate the api routes, so that you have the api routes protected by OAUTH and the api routes protected by the session, both of them pointing to the same controllers. The method was explained here: https://stackoverflow.com/a/22964736/435026