Can RestSharp obtain an oauth2 access token from IdentityServer/DuendeServer for a user programmatically if given username/password? - api

We have Duende server for our UI and users provide their username and password and obtain an access token that is then used by our SPA app to call api's with the access token issued by our identity server.
I'm in a situation where I need to call the same API from a script and was wondering if RestSharp has some capability to obtain an access token if provided certain information (perhaps the users email/password etc that are typically entered into an interactive website) ?
I see that the RestSharp has some OAuth related "authenticators" but the documentation is unclear exactly what they achieve. I also dont see it mentioning anything about an email address and password.
I'm wondering if theres an option that is different than me generating a JWT elsewhere and supplying it directly to restsharp. I'd love if there was a programmatic way to generate the token directly from the IDP.

RestSharp documentation doesn't make it secret about how authenticators work. Both OAuth2 authenticators only add the necessary header or query string using the token you provide, but they don't request the token.
Duende server documentation explains in detail how to get a token based on the password grant (which is using the username and password).
Although the OAuth2 spec is stable, each API vendor has its own limitations. For example, Twitter API v2 only supports the client_credentials grant type. Therefore, it's not easy to create a generic OAuth2 client.
Still, it's quite easy to amend the Twitter authenticator sample from the docs and extend both request and response models to support the Duende server token request endpoint.

Related

What's the proper way to implement a "static" authorization token feature using OIDC (or OAuth2)

I am exploring possible solutions for creating something like "API Keys" to consume my API. The goal is to allow for users to generate one or many "API Keys" from the web app and use the static generated key from the CLI app.
The web app and the client app are already using standard OIDC with JWT tokens for authentication and authorization using RBAC (role-based access control). The CLI app can already authenticate the user through the standard browser flow (redirects the user to the browser to authenticate and exchange the token back to the client).
The "API Keys" solution I am trying to achieve should have some fine-grained options where it won't authenticate as the user, but will authorize the client on behalf of the user (something like the GitHub Personal Access Token).
To me it seems like a "solved problem" as multiple services provide this kind of feature and my goal is to do it the most standard way possible using the Oauth2/OIDC protocols but I can't find details on what parts of the protocols should be used.
Can anybody provide any guidance on how it is supposed to be done using the Oauth2/OIDC entities?
Can I achieve it by only using Role-based access control or do I need Resource-based access control?
It went through the path of creating a new client for each "API Key" created, but it didn't feel right to create so many clients in the realm.
Any guidance or links to any materials are appreciated.
Can anybody provide any guidance on how it is supposed to be done
using the Oauth2/OIDC entities?
OIDC is based on OAUth 2.0 so after user login you have id tokens, access token and refresh token on the backend side. To generate new access token without asking user for authentication data you should use refresh token: https://oauth.net/2/refresh-tokens/
Can I achieve it by only using Role-based access control or do I need
Resource-based access control?
resource-based access control is more flexible solution here, but if you business requirement is not complex, then role based might be enough.
It went through the path of creating a new client for each "API Key"
created, but it didn't feel right to create so many clients in the
realm.
It is one application so you should use one client with specific configuration for access token and roles/permissions for users.
Update:
We can use GitHub as an example:
User is authenticated during login
for OIDC code is exchanged for id token, access token and refresh token
session for user is set for web browser
User can request access token
in GitHub authenticated user can request github.com/settings/personal-access-tokens/new endpoint
request is accepted, because user is authenticated based on session
backend service responsible for returning access token can obtain new access token using refresh token from point 1.
access token is returned to GitHub user
To call your API in an OAuth way, CLI users must authenticate periodically. Resulting access tokens can be long lived, as for GitHub keys, if you judge that secure enough. The access token returned can be used exactly like an API key. There may be a little friction here between usability and security.
CONSOLE FLOW
The classic flow for a console app is to use the Native Apps Desktop Flow from RFC8252. This involves the user interactively signing in using the code flow, then receiving the response on a loopback URL. It is an interactive experience, but should only be required occasionally, as for GitHub tokens.
API KEYS
The access token returned is sent in the authorization header and you can use it as an API key. Access tokens can use a reference token format. to make them shorter and confidential, to prevent information disclosure. These will be more natural in a CLI.
API AUTHORIZATION
When your API is called, it must receive access tokens containing scopes and claims, to identify the user. This will enable you to authorize correctly and lock down permissions.
{
sub: 586368,
scope: repos_write,
topic: mobile,
subscription_level: silver
exp: ?
}
TOKEN REFRESH
Sometimes CLI access tokens are long lived, for convenience. A more secure option is for the CLI to use token refresh. It can then store a refresh token in OS secure storage, then renew access tokens seamlessly. My blog post has some screenshots on how this looks, and a desktop app that does not require login upon restart. The CLI needs to deal with expired access tokens and handle 401 responses.
DYNAMIC CLIENT REGISTRATION
Some developer portal scenarios use DCR. It is another option in your security toolbox. It could potentially enable a silent client per CLI user:
User runs a standard authentication flow with a DCR scope
This returns an access token that enables client registration
The resulting token is used to register a new client
This could potentially be a client ID and client secret used in a CLI
Afterwards, the user and client are bound together. Probably not immediately relevant, but worth knowing about.

How does OAuth work API to API without interactive users?

I have a background task that runs periodically which needs to connect to a customer's Apigee OAuth2 protected API. From my understanding of OAuth2, a user must go to a sign in page on Apigee, and it will redirect to a return Url with a token. This is the way I have used previously on website projects. But in this scenario, there are no users, no website, and no return Url, it is just some code making a http request.
Is the above possible to do? Every google search I make is all about users logging in manually and getting a token to a return url.
I found some mention of 'Flows' and maybe there is some other 'Flow'? but its really hard to get a clear understanding of how it works because guides are focused on user interactive websites.
OAUTH 2.0 is an industry-standard for authorization. OAUTH 2.0 supports many authorization grant types, namely they are;
Authorization Code
Implicit
Resource Owner Password Credentials
Client Credentials
[Note that you may come up with your own custom grants as well if you are building or extending your authorization server - however it is beyond the scope of this question]
In the example you have provided, you are using the Authorization code grant type where you redirect to APIGEE and getting an authorization code. The APIGE server acts as the "intermediary between the client and resource owner" in OAUTH 2.0 terms.
For your new requirement, you should consider using the client-credentials grant type where the client is provided a client key and a secret. The client has the responsibility of calling the authorization server (like APIGEE in your previous example or anything else) and getting a token and then using that token in the subsequent requests.
I recommend you to read the ietf standard for oauth 2.0 to get a better understanding - Refer https://www.rfc-editor.org/rfc/rfc6749.
Make sure to read on "Roles" in this link well before diving onto the content of this document.
Good luck!

Securing an existing API with our own solution

I have to design a mobile application that interacts with a provided API to exchange data and info, and I've read about API security, Oauth 2, tokens, .... etc, but something still not clear to me, the following are the important points:
API provided by a 3rd party as a black box, no security implemented,
so you can query for data belongs to any user.
a user should use our application, sign in with a user/password and get access to his data only. (must be very
secure, because we should pay a lot if security was broken)
the solution needs to be implemented and self-hosted, not from a third party or cloud provider.
example of an API call:
....base url...../{subscriber-ID}/offers
the above call get the suitable offers for a subscriber whose ID is {subscriber-ID}, so obviously, without security, I can query offers for any subscriber, but my goal is to link between user/password and querying only data related to the desired user.
I read a lot, but I'm confused since I'm new to API security.
so where should I start? how can I benefit from Oauth 2 in my case? just need a roadmap, not how to implement.
oAuth2 using spring security is a solution for this requirement.
There are 4 grant types in oAuth2 which is meant for different scenarios.
client credential : the consumer (app) make calls to back-end using the bearer token created using apikey(or clientId) and secret only. Mostly used for anonymous calls where generic information is retrieved.
Resource owner password credential (ROPC) : the consumer (app) make calls using the bearer token created using apikey, secret, username and password. Mostly used when you(your authorization server) already know the users(user database is handled in your own system).
Authorization code : the consumer (app) make calls using the bearer token created using an authorization code. The authorization code is provided by a 3rd party (which actually has/manages the logged in user data) and the created authorization code linked to the logged in user. Google and Facebook log in for various sites is a typical example. Facebook/Google gives an authorization code for those websites and they exchange that code for a token.
Implicit grant : Mix of password credential and authorization code. Instead of authorization code, you get a bearer token from the 3rd party authorization server.
I have been searching a lot for a simple sample code for an authorization server, but never found one. So, I tried to create it myself which you can find here : https://github.com/abbinv/oauth2Server. Only ROPC and Client Credential is implemented.
It is not a 'beautiful' code. But i think you will get the basics.

What is the difference between OAuth based and Token based authentication?

I thought that OAuth is basically a token based authentication specification but most of the time frameworks act as if there is a difference between them. For example, as shown in the picture below Jhipster asks whether to use an OAuth based or a token based authentication.
Aren't these the same thing ? What exactly is the difference since both includes tokens in their implementations ?
This is a good question -- there is a lot of confusion around tokens and OAuth.
First up, when you mention OAuth, you are likely referring to the OAuth2 standard. This is the latest version of the OAuth protocol, and is what most people are specifically talking about when they say 'OAuth'.
The OAuth protocol supports several different types of authentication and authorization (4 to be precise).
Secondly, the OAuth protocol works by authenticating users via tokens. The idea here is this:
Instead of having your user send their actual credentials to your server on every single request (like they would with Basic Auth, where a user sends their username/password to the server for each request), with OAuth you first exchange your user credentials for a 'token', and then authenticate users based on this 'token'.
The idea of OAuth is that by requiring users to pass their confidential credentials over the network less frequently, less bad things can happen. (This is the idea, anyhow.)
Now, here's where tokens come into play: the OAuth spec is built around the concept of tokens, but DOES NOT SPECIFY WHAT A TOKEN IS.
In the most 'general' sense, a token is just a string that uniquely identifies a user. That's it.
People realized this, and developed a new standard for creating tokens, called the JSON Web Token standard. This standard basically provides a set of rules for creating tokens in a very specific way, which makes tokens more useful for you in general.
JWTs let you do things like:
Cryptographically sign a token so you know that a token wasn't tampered with by a user.
Encrypt tokens so the contents cannot be read in plain text.
Embed JSON data INSIDE of a token string in a standard way.
Now, for the most part: pretty much everyone in the development community has agreed that if you're using any sort of OAuth, then the tokens you're using should be JSON Web Tokens.
OK! Now that we've covered the backstory, let me answer your question.
The choice you're making above is whether or not you want to enable the full OAuth2 specification for authentication / authorization (which is quite complex), or whether you simply want some basic 'token authentication'.
Because the OAuth protocol provides multiple different ways to authenticate in a STANDARDS COMPLIANT way, it adds a lot of complexity to most authentication systems.
Because of this, a lot of frameworks offer a 'dumbed down' version of the OAuth2 Password Grant flow, which essentially is a simple method where:
A user sends their username/password to your server at some URL like /login.
Your server generates a JWT token for the user.
Your server returns that token to the user.
The user stores this token in their cookies, mobile device, or possible API server, where they use it to make requests.
Again: the flow above is NOT OAuth compliant, but is a slightly simpler version that STILL uses tokens.
The main point here is that tokens (JWTs) are generally useful, and don't NEED to be paired with the OAuth flow.
I realize this is a wall of text, but hopefully it answers your question in more depth =)
OAuth is a specification for authorization not authentication
OAuth 2.0 is a specification for authorization, but NOT for authentication. RFC 6749, 3.1. Authorization Endpoint explicitly says as follows:
The authorization endpoint is used to interact with the resource owner
and obtain an authorization grant. The authorization server MUST first
verify the identity of the resource owner. The way in which the
authorization server authenticates the resource owner (e.g., username
and password login, session cookies) is beyond the scope of this
specification.
Only use OAuth if you want to give access to a third party service to your apis. Even when you are using OAuth you would need some kind of authentication (token based or session based etc) to authenticate the uses. OAuth is not designed for authentication.
see this question.
When you are requesting resource from a secured web service, you can provide an authentication token on the call. The token acts as "secret code" for accessing the resource.
OAuth is just specific type of token based authentication method.

Adding OAuth 2.0 authentication to a RESTful API

I have an API that requires authentication via OAuth 2.0. I originally anticipated using HWIOAuthBundle, however from investigation this is more to do with hooking up 3rd parties into Symfony's security/auth mechanism and does not provide the required mechanism for validating OAuth 2.0 Authorization headers.
I then found some information about FOSOAuthServerBundle which enables an application to become it's own OAuth 2.0 provider as well as providing the required security mechanisms to validate Authorization headers.
However the problem is that I would like integrate the OAuth 2.0 provider (authorisation server) in an external application (which contains the user base) and not include it within the API. Which will provide some mechanism for performing the token verification against this external app via (another) RESTful API.
Points:
RESTful API requires OAuth 2.0 authentication.
OAuth 2.0 authorisation server to be situated in a separate application.
I feel I should use Implicit grant and call the authorization server on each request to validate that the token is correct.
Is my thinking correct?
As far as I undesratnd your requirement, you require to authenticate your APIs via external OAuth Authorization Server:
Client needs to provide the access token retrieved in the above steps
along with the request to access the protected resource. Access token
will be sent as an authorization parameter in the request header.
Server will authenticate the request based on the token.
If token is valid then client will get an access to protected resource otherwise access is denied.
here is an example which might help you to achieve your requirement. Check this document .
Or simply, you can do with Jersey and Oauth
Also, you can check Apache Oltu and figure out the way to achieve your requirement.
A lot of the big companies like Google, Facebook etc have a separate authorization server from the API server. Check out Google's OAuth authorization flow below
You can also check Google's OAuth Documentation for the details.
So all you would need to do is implement a OAuth Provider so that you can authorize against that provider. There's a list of libraries available on the OAuth website: http://oauth.net/code. You can specifically look here; there is an example for running an OAuth Service Provider in Java.
oAuth can most definitely be a server other than your application server. Below is a picture of what the authentication sequence would look like:
-- Obviously, if the forum can't decode or validate the token, the forum would return a 401 status code instead of a 200 status code.
As long as your oAuth server & the Forum share the same public key, you're more than okay with splitting your oAuth Server & your application.
In fact, take a look at jwt.io. Paste the token you get from the oAuth server into there. It should be able to decode the token right away. Then, you can put your public key into the 'secret' text box to verify the token is verified.
Your application (Forum, in this example) should be able to do the same:
1) Grab the token from the Authorization header of the request
2) Decode the token
3) Check the expire date
4) Verify the token using the oAuth's public key
5) Return successful status code or a failure status code