How to Authenticate a user by recovering a token on their behalf - Azure AD - authentication

My I am trying to deploy azure AD to my application because I want to expose some of my APIs to users but I need to make sure only people that are authorized can use the resource.
I have never worked with azure AD before and I am a little lost in all the documentation.
What I need is to be able to recover a token on behalf of the user in order to authenticate them. The application does not have any webpages and I do not want to introduce any. I want to be able to grab the token, authenticate the user, and then release the resource. I expect that the endpoint will be accessed through python, java or postman.
Example of basic flow:
call security function/api in app
validate user cred (or any other type of validation)
return token if authenticated
validate token and return response
5.authentication allows user to call apis
I have just explored the authorization code pattern that azure AD offers but this requires an interactive step from what I was able to test so its no good.
I would like to be able to do something like the example flow
In case my question hasn't clued you in I am very new to this so any help is appreciated
Thanks in advance

I agree with #Gopal you can make use of client credentials flow that does not require user interaction to call an API.
You just need to enter Azure AD client application’s ID, Secret, scope to generate the access token and use that access token to call the API via Postman or in your code.
I created one Asp.net core API in VS studio and used Azure Ad authentication to call the API.
I tried accessing this API via Postman App with different flows that you can try :-
Client Credentials flow:-
GET https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
grant_type:client_credentials
client_id:<appID>
client_secret:<secret>
scope: https://management.azure.com/.default
Results :-
API can be accessed by the Access token generated by the client app with its secret and scope.
Alternatively, you can make use of Implicit flow which will ask for user credentials via browser.
Implicit flow :-
Here, Your log in page pops up while asking for access token and you need to enter user credentials to get access token and fetch API.
Get the token and hit the token to fetch the API like below :-
Browser Pop up:-
Access Token:-
Now, copy our API URL from browser and try to access the API :-
Results :-
You can find the code samples below :-
https://learn.microsoft.com/en-us/azure/active-directory/develop/sample-v2-code#web-api

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.

REST API access from inside SSO

OK so I have an account using SSO credentials and the data within this SaaS app is available via a REST api using OAUTH2 but the API is not SSO friendly or enabled so how do I (if possible) access the data via the API but the only credentials I have are managed by the SSO., I do have my api key and secret and I can generate my access token in python from another non sso account but the sso account even tho I have the username and password I cannot get anything but a 401.. any help?
I might add , I am just an end user and have ZERO access to the actual API or data set but I can create and edit users and access on the SaaS app I cannot however change anything with the SSO or AD
I have tried using username#domain.com/token , I have also tried org\username and password, I have tried requesting different access-types from the OAUTH2 endpoint and the only recognized type is password. And I have tried every combination of the above trying to get the data from the API
If you are trying to access the third party REST API via OAuth2 then you'll need to check with the third party team if you are authorized to access that API, they may have to provide some additional permission to allow the access. If you are getting 401 then you don't have the correct credentials, please verify.

How to protect frontend and rest API with Keycloak

I am very new to Keycloak server and want to use it to protect my front-end app and the backend rest API which are also open over the internet. So far what I understand and did is to create 2 clients on Keycloack, 1 is for frontend which used Client Protocol(openid-connect) with access type(Public) and then in client side i am using adopter to redirect the users to Keycloak login page and authenticate and get token. Now for the backend(rest-apis), I have created a separate client which again use Client Protocol(openid-connect) but with access type(confidential) and in Authentication Flow: both Browser Flow and Direct Grant Flow are direct grant and after that i get client-id and client-secret to call Keycloak rest api.
Now i want that when user are authenticated from frontend and get the token and send in header request to my rest API, here i call some Keycloak rest api to verify this token by providing client_id and client_secret.
I am using following rest api from Keycloak to verify the token which i generated at frontend:
http://localhost:8120/auth/realms/evva_realm/protocol/openid-connect/token/introspect
but result is getting like that:
{
"active": false
}
It my be i am using some wrong api OR the whole archetecture to verify and protect my backend apis are not correct. Can someone help me to understand where is the problem?
#user565 I found this medium post that works for me. I believe that you can benefit from it as well.
It basically creates two clients, one for the backend, and another for the frontend. The catch is that they share the same roles by leveraging the client scope, roles, and composite roles features.
Hope it helps: https://medium.com/devops-dudes/secure-front-end-react-js-and-back-end-node-js-express-rest-api-with-keycloak-daf159f0a94e

OAuth 2 authentication for both iframe and api

I'm integrating several web sites/services into my application. I use iframes (or webview for Vue Electron) for UI integration and I also use API to implement cross-communication between those services.
At the moment I have to go through OAuth 2 authentication twice for each service: once as part of natural authentication in iframe and another when I ask the user to give me access to this service (for api reasons).
Is there any way to streamline this process?
The state of the art response would be to modify your application completely.
You should have 1 SPA application and not iframe
This application would authenticate to get OAuth2 token
This application would then call the backend (access multiple backend, or access on api management layer that call backends).
Thing is, with this you can have 2 strategies :
give all permission (scope) at 1st authentication
give the smalled scope possible at 1st authentication, then when needed "reauthenticate" (in fact validate new scope) to get new access token
When an API want to call another API, you have also 3 strategies:
you simply use the same client token the API receive to the service your API call (no human interaction needed)
your API generate a token from a service account (using ROPC authentication scheme) or via a client credential scheme (the access token will be valid but usually not be bind to a real user), (no human interaction needed). (the API will be the client of the 2nd API)
your identity provider have an endpoint to transform access token : Your API can give the client access token, and authorization server will transform this with the client_id of your API. You send this token to 2ndAPI ( token will show subject of your UI application, but client ID will be the 1st API clientId) (no human interaction needed)
Now if you use IFrame with multiple sub-application on the same domain (the domain need to be exactly the same!), it is possible to share the same access token for instance via local storage. (security is not top notch)
You will probably need to authenticate with a bigger scope list sometime but it is your only option. You will simulate a single page application, but issue is that you will have potentially different client_id depending first application you authenticate to.
Edit: Multiple authorization server
From your comment, you have multiple authorization server. One strategy could be to ask user to authenticate, your application can then get an access_token and a refresh_token.
Depending on your authorization server, refresh_token can be used a lot / on a long period of time, so that if you store it somewhere, the next time the user visit your application, your application can silently get an access_token from this refresh token. Your application have then access to remove api without newer interaction from your user.
Of course, this means you have to save this token the most safely you can.
By using OpenID Connect you could combine authentication and authorization in a one step and get both an id_token to logon your user to your app as well as an access_token to access APIs in a single authentication response.

Can't modify user private data with Client Credential Flow by Spotify Web API

Is there any method to modify i.e. playlist by Web API by with console based application in Client Credential Flow ?
https://developer.spotify.com/web-api/authorization-guide/#client-credentials-flow
Propably not, but maybe I am wrong ? I want to modify only my user's data.
Here I created issue at API specification
https://github.com/spotify/web-api/issues/165
One of the benefits with the Client Credentials oAuth 2.0 flow is that applications can make authenticated requests to a web service without a need to involve an end user. Since a user isn't involved, the requests that can be made from the application is limited. For example, using Spotify's API, you can still make requests to retrieve track metadata, playlist contents, and search for albums. Any endpoint that requires a scope can't be used since it requires user interaction.
So using Client Credentials simply doesn't make sense if you're interested in making requests on behalf of a user, or if you want to access private data since the user needs to give you permission first.
You need to use Implicit Grant or Authentication Code Flow for this. I advise that you read further about the supported oAuth 2.0 flows in the Authorization Guide. One of the benefits of using the Authorization Code flow is that you'll also retrieve a new refresh token, which you can use to retrieve access tokens indefinitely. It however requires you to write a web service that accepts an authorization code and exchanges it for the tokens. The Implicit Grant flow doesn't return a refresh token, so it's only possible to use for one hour until the access token has expired.