Why use Client Credentials flow? - api

I've been looking at using oauth2 client credentials grant to secure my API (all users will be trusted 3rd parties). I'm following the same approach as paypal here: https://developer.paypal.com/docs/integration/direct/paypal-oauth2/
However, I see that HTTP:// basic auth is used to acquire a bearer token. Then the bearer token is used to secure the API calls.
What I don't understand is, if you're going to trust TLS and http: basic auth to retrieve the bearer token - why not just use http: basic auth for the API calls? What is the benefit of using bearer tokens?
What am I missing?

Adding to what Ankit Saroch is saying, going the OAuth way with Tokens may open up other possibilities in the future; say you may want to extend the flow to include User information. By only validating tokens, this means you will probably not need to change the token validation (which is simple) in your service, but rather only the authentication and authorization steps.
But obviously you're right in what you are saying: The Client Credentials OAuth Flow is not more secure than simply using techniques like API Keys or Basic Authentication. All of those rely on the Client being confidential (it can keep its credentials to itself).
The OAuth Spec (https://www.rfc-editor.org/rfc/rfc6749#section-2.1) talks about these Client Types. In total, it's worth reading the spec actually.

As per The OAuth 2.0 Authorization Framework: Bearer Token Usage
The access token provides an abstraction, replacing different
authorization constructs (e.g., username and password, assertion) for
a single token understood by the resource server. This abstraction
enables issuing access tokens valid for a short time period, as well
as removing the resource server's need to understand a wide range of
authentication schemes.
The server that is authorizing the request and giving you the Bearer Token, may be different from the server that actually controls the resources that you are trying to access.
As per the RFC, they have been shown as two different entities. The one giving you the Bearer Token is Authorization Server and the one serving the resources is Resource Server.

Related

Using openid-connect for authentication spa and rest api

I have an API Server (Resource server) and multiple apps, Web GUI (SPA) and a Desktop client and maybe more coming.
I'd like to use openid-connect besides http basic authentication for my API Server.
It should be configurable which openid provider to use. My own, facebook, google...
I only want to do authentication, I do not need their API. I only need some profile data like email or firstname.
Let's say I have configured google as my IdP and I'm currently using my Web GUI (SPA). I need to login, no problem, according to https://developers.google.com/identity/protocols/OpenIDConnect I redirect the user to google, get my authorization code and the Web Gui (SPA) gets an id_token and access_token from google.
No problem so far, but now the SPA has to work with my API Server and the API Server needs to authenticate every request (since it is a stateless rest api) coming from the Client (WebGui SPA) and needs to know which user actually did this.
A
So the access_token from google is meant to be used to access google api's right? But I also could just pass this access_token with every request to my api server and the api server calls https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=xxx to verify the access_token and get the account name (mail). But this doesn't sound right, does it?
B
I also have and id_token which I can verify without calling google server everytime. So could I also just pass the id_token as bearer with every request to my api server and the api server can verify the id_token? But according to openid-connect spec the access_token is actually the one which just get passed to the api server and the id_token must stay on the client.
But then the id_token would be completely useless to me, the API server needs to know who the user is, the client (Web GUI) doesn't really care.
C
Or since it is my own API Server, does my API Server actually needs to implement the whole oauth2 system by itself, just not authentication but creating access_token and more. So I would have a /api/tokensign to which I can pass the id_token from google, the API verifies the id_token and creates an access_token for my WebGUI (SPA). And this new access_token can be passed as bearer to every api request. This actually sounds as the best solution according to specs, but do I really need to implement oauth2 by myself into my API? Sounds like a heavy addition since A and B could also be implemented.
My rest-api needs authentication with every request so is A, B, C the right approach? Please don't tell me this is opinion based, it is not.
What is the right way using oauth2/openid-connect for authentication?
You can use all three methods you have mentioned above, but indeed with some considerations. I will explain them with regards to available specifications.
Scenario - Two systems S1, S2
S1 - Identity provider
S2 - API endpoint
What you need - Trust and use 'Tokens' issued by S1 to access S2
Explanations for proposed solutioins A, B and C
A - Verify tokens issued by S1 for each call
This can be done using the RFC7662 - OAuth 2.0 Token Introspection endpoint. This validation is valid by the specification so yes you can use the token verification endpoint.
Advantage for this method is that, if a token is revoked, the effect is instantaneous. The very next API call will fail. But indeed there's the implication on performance. You need an extra verification service call.
Note that you do not need to get the account name from this verification response. It could be taken from ID token and could be used to verify for extra protection.
B - Trust tokens issued by S1 for each call
Now this approach is something extended from RFC6750 - The OAuth 2.0 Authorization Framework: Bearer Token Usage. You can indeed use ID toke to authenticate and authorise an end user. This link contains a good explanation on the ID token usage as a bearer token.
You can indeed verify the validity of token using MAC and even encryption. But be mindful to use short lived tokens and to always use TLS. And be mindful about refreshing tokens.! Because according to openID connect specification, ID token is not a mandatory item for a refresh token request.
C - A wrapper for federation
For this you can write your own solution or use an existing solutions (ex:- WSO2 identity server). This identity server will configured to choose the identity provider on your application (client like desktop app or web app). Identity server will do the necessary redirects and provide you the required tokens. But indeed you will need to use introspection endpoint to validate the token validity.
If you go one step ahead of this solution, you can try to implement a code exchange mechanism. You can exchange the token carry from external to tokens issued internally by one of your system (ex:- Google access token to your internal access token). The advantage of this approach is you have control over validation. Also since subsequent token validations are done internally, there should be a performance improvement.
Hope this explains some doubts you have.

What are the main differences between JWT and OAuth authentication?

I have a new SPA with a stateless authentication model using JWT. I am often asked to refer OAuth for authentication flows like asking me to send 'Bearer tokens' for every request instead of a simple token header but I do think that OAuth is a lot more complex than a simple JWT based authentication. What are the main differences, should I make the JWT authentication behave like OAuth?
I am also using the JWT as my XSRF-TOKEN to prevent XSRF but I am being asked to keep them separate? Should I keep them separate? Any help here will be appreciated and might lead to a set of guidelines for the community.
TL;DR
If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0. On the other hand, if there are lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.
As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format. It defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.
Being self-contained (the actual token contains information about a given subject), they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route, the only thing a party must present to be granted access to a protected resource is the token itself, and the token in question can be called a bearer token.
In practice, what you're doing can already be classified as bearer token -based. However, do consider you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply relying on the Authorization HTTP header and using the Bearer authentication scheme.
Regarding the use of the JWT to prevent CSRF: Without knowing exact details it's difficult to ascertain the validity of that practice. To be honest, it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.
One final piece of advice. Even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.
Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.
(source: RFC 6819, section 5.4.1)
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).
Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.
XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.
JWT (JSON Web Tokens)- It is just a token format. JWT tokens are JSON encoded data structures contains information about issuer, subject (claims), expiration time etc. It is signed for tamper proof and authenticity and it can be encrypted to protect the token information using symmetric or asymmetric approach. JWT is simpler than SAML 1.1/2.0 and supported by all devices and it is more powerful than SWT(Simple Web Token).
OAuth2 - OAuth2 solve a problem that user wants to access the data using client software like browse based web apps, native mobile apps or desktop apps. OAuth2 is just for authorization, client software can be authorized to access the resources on-behalf of end user using access token.
OpenID Connect - OpenID Connect builds on top of OAuth2 and add authentication. OpenID Connect add some constraint to OAuth2 like UserInfo Endpoint, ID Token, discovery and dynamic registration of OpenID Connect providers and session management. JWT is the mandatory format for the token.
CSRF protection - You don't need implement the CSRF protection if you do not store token in the browser's cookie.
It looks like everybody who answered here missed the moot point of OAUTH
From Wikipedia
OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.
The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access
There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points
You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general
Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials
find the main differences between JWT & OAuth
OAuth 2.0 defines a protocol & JWT defines a token format.
OAuth can use either JWT as a token format or access token which is a bearer token.
OpenID connect mostly use JWT as a token format.
JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.
Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.
You can read more on this here
OAuth or JWT? Which one to use and why?
Jwt is a strict set of instructions for the issuing and validating of signed access tokens. The tokens contain claims that are used by an app to limit access to a user
OAuth2 on the other hand is not a protocol, its a delegated authorization framework. think very detailed guideline, for letting users and applications authorize specific permissions to other applications in both private and public settings. OpenID Connect which sits on top of OAUTH2 gives you Authentication and Authorization.it details how multiple different roles, users in your system, server side apps like an API, and clients such as websites or native mobile apps, can authenticate with each othe
Note oauth2 can work with jwt , flexible implementation, extandable to different applications
JWT tokens require, at most, a one-time communication between the resource server and the authorization server at runtime. The
resource server needs to request the authorization server for the
public key to decrypt the JWT tokens. This can be done at resource
server startup. This can even be stored in the resource server in a
properties file avoiding the query at all.
OAuth2 solve a problem that user wants to access the data using client software like browser-based web apps, native mobile apps, or
desktop apps. OAuth2 is just for authorization, client software can
be authorized to access the resources on behalf of end-user using an
access token.
OAuth2 can be used with JWT tokens or access token which is a bearer
token.

In OAuth 2 why is there need for an Access Token when there is the Authorization Code?

In OAuth 2 the client app exchanges an authorization code for an access token. And with the access token, the app can make API calls. However, I don't really get why OAuth 2 has this step; it seems like an extra step.
One reason I can think of is that the authorization code is given through a redirect call on the client side, so it has the potential to be compromised, thus it's short lived; whereas the access token is given server-to-server.
That is true, but there is also the secret API key that the app sends. Then why couldn't same be done with the authorization code?
Say there was no access token but just the authorization code. Then even if someone gets the authorization code, they wouldn't be able to do anything if the OAuth server also checked the secret key along with the authorization code.
It should allow the OAuth server to:
Make sure the request was made by the correct app (authenticate)
Determine what types of permission were granted (authorize)
Ability to get access_token directly (Implicit grant type) is required in the cases of JavaScript clients or web applications running in a browser. Because, these clients are not secure based on the options available for saving the client secret. The client id and secret are required to exchange authorization code for an access_token.
These two grant types exist to provide various levels of security when implementing authentication.
If the resource served by the API is extremely sensitive then you want at most security, which is provided by Authorization Code flow. In this grant type you validate the client (server side API or a mobile client) and the resource owner (user) before granting access to the resource. The access_token is not even exposed to the browser/ user (since a stolen token can give access to the resource), thus giving high degree of security. This flow is complex and involves more round trips to the authorization server, but, provides more security.
If you don't need that kind of security on a resource you can use Implicit grant type where the browser/ user has access to the token. This flow is simple with only one trip to authorization server. It will not validate the client. No need to save the client secret with the browser.
Hopefully this makes sense. Please let me know if you have any questions.
Thank you,
Soma.

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.

RESTful API security

I would like to develop RESTful API for my web application. Client have to be clear JS + HTML and user have to somehow authenticate in system. I've read few articles about security and RESTful API but some point still are not clear for me. As I've understood at the first step user have to provide his credentials to server. After that server have to validate user credentials and if they are valid, sent some encoded token to user (assume it will be [user key]:[user IP]:[token creation time]). After user authentication client have to sent this this key with each API call. That's how I've understood RESTful API authentication principes.
With such solution I assume that token can be stolen and another user can access to secured user data (even if IP is included to access token and there will be validation on each request). For this purpose I plan to include token creation time but as I understand with such solution I have to renew access token each time when it expiring - in this case it's not clear for me how to implement "remember me" functionality.
It's not clear for me how to implement 100% safe authentication for my RESTful API. Maybe I'm missing something. Or maybe my understanding of authentication principes is wrong.
It depends from what authentication scenario you are using. For example when dealing with in ASP.NET MVC + REST with Basic Authentication it will produce for you token which is in the fact Base64 encoded string '{username}:{password}'. And you are right it could be stolen, that's why for Basic Auth HTTPS is must, as token goes throw Authentication header with Basic schema.
For REST security most suitable and secure are OpenId and OAuth. Just don't reinvent wheel and use already existing standards. OAuth in compare to OpenID includes not only authentication but authorization as well. OAuth already describes all nuances with token renew and token creation time and so on.
Now practical how to implement OAuth in REST. First of all read standard. For your case read with attention Implicit Grant flow, because standard has multiple flows for different client with different trust level and security.
https://www.rfc-editor.org/rfc/rfc6749
And after that you can try some already implemented library in technological stack you are using either Java or .NET. For client it is not so important to use library in compare but for server implementation
About potential security problem read here https://www.rfc-editor.org/rfc/rfc6749#section-10.
Some think that OAuth 2.0 is less secure that OAuth 1.0, and it is also dependant from token format. Anyway access token should be passed in HTTP Header and through HTTPS as well as clientid should be stored and passed securely.