Identity Server 4 (with external Azure AD auth) token is not valid in Graph API - azure-active-directory

I am switching my application from Azure Active Directory authentication to authentication with Identity Server (using Azure AD as external auth). The authentication and authorization part is implemented and my web API successfully validates token and give me what I'm asking.
Our application also uses external APIs, such as Graph API and SharePoint Online which require Azure AD token. E.g. when I go to https://graph.microsoft.com/v1.0/me from my JS application with token that I get back from Identity Server, Graph API response is
401
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "ce7651bb-5dc4-49e9-90ff-02df440ed4ad",
"date": "2017-08-11T08:53:12"
}
}
}
I expected that because Identity Server is giving me his token, and not passing the existing token that is provided by Azure AD. I copied all the claims from Azure AD token into identity server token, but no changes.
What would be the right approach to enable my application to continue using APIs which require Azure AD token?
EDIT:
What I'm hoping for is this.
Click login button on Js (or any other client app)
Redirect to Identity Server login screen
Click on Azure AD external auth
Redirect to Microsoft login page and enter your credentials there
Redirect to Identity server app
a. I started Fiddler and see that "Microsoft" redirect to {IdentityServerAppUrl}/signin-aad (I suppose this is because I configured CallbackPath property on OpenID Connect options). This request carry a cookie idsrv.external. I'm not sure but I think inside is access token from Azure AD. I don't know how to decode this. I tried with base64, but it is not working.
b. When this request is finished redirect is made to {IdentityServerAppUrl}/account/ExternalLoginCallback. In this action method I check with debugger all fields and data in request but I can't find token from AAD. I'm hoping to get token and put it in additional calims.
Identity Server app redirect to JS client app with its own token and additional claim that contains Azure AD token that is valid on graph API and SharePoint.
First I would like to locate Action method or middleware that handle {IdentityServerAppUrl}/signin-aad?
Second, is there any way to get token from Azure AD or any other external provider inside {IdentityServerAppUrl}/account/ExternalLoginCallback Action method?
Be aware that I'm new to this kind of stuff and maybe I'm totally wrong with this thinking.
I manage to do Azure AD authentication without Identity Server, but know we have request to have multiple external providers and I'm hoping to handle all authentication in one app. If one day I get request to have additional external provider I need to add to just in one place.

You need to retrieve an access token from AAD for the Graph API - how that exactly works, check the Microsoft documentation.
Once you have that access token, you can return it as a claim in either the IdentityServer identity or access token (depending if you want to make it available to your front or back-end).
You can also try that first in a simple MVC app to remove the moving partsy - and once you have the AD part working, move your code to the app using the identityserver middleware.

I am also looking for an answer to this question. However, I think it should work a bit differently. IdentityServer gives you a JWT that you can use to authorize to the recources that make up your app. E.g.: yourAPI-1 and yourAPI-2. With the JWT you can pass on the identity. Microsoft Graph is an external resource. Therefore we would need the access token form the Graph API as a claim or external resource, same way as you'd receive an access token for an internal resource.
I would guess that there should be a way of forwarding whatever information you get from the identity provider (Azure AD) to IdentityServer for your client (JS app) to pick up. I am facing the same problem here.
There is another thread about this topic that caught my attention which I will look into. It requires to build your IdentityServer from the source with a few modifications: ASP.NET Identity (with IdentityServer4) get external resource oauth access token
I will let you know what the outcome is and push it to a git repo that you can use if it works:

Related

How can I get access- and refresh-token from Azure AD B2C using a certificate?

Context
We are transitioning our Spring Boot application (with Angular frontend) from Spring's build in OAuth2 based security to Azure-AD. This is working well for clients we can update right away (mainly the B2B clients). However some (most B2C) clients can not easily be updated at the moment. In time this will happen, just not now. So I need a solution for the mean time.
Our idea
We proxy the request for the Azure tokens via the Spring Boot backend. From the client's point of view, it would look like the old solution. Username and password would be authenticated against the backend's database. Upon successful authentication, a certificate would be looked up for the user and this would be used to aquire an access and refresh token from Azure-AD B2C containg also a token for B2B.
That token would be wrapped into Spring's old OAuth2AccessToken and sent back to the client. The refresh request would be proxied in a similar way.
I have the refresh part working based on this: Web sign in with OpenID Connect in Azure Active Directory B2C -> Refresh Token
The problem
Using Microsoft's Graph API I can get an access token, but the part of the MsalToken extends AccessToken that is public (AuthenticationResult implements IAuthenticationResult) does not let me access the refresh token even if I request scope offline_access and if it is contained in the result.
Questions
Are there security concerns that make this idea a fundamentally bad idea? I'm aware that this requires trusting the backend, but that was the case so far. To me that does not seem to make it worse.
Is there a way to get an access- and refresh-token for a user be presenting the users certificate (or another none-interactive method - but we do want to use MFA as well for updated clients). I tried using Microsoft's Graph API, but a direct web-request is fine too.

Spring OAuth2 Single Page Application Integration to Azure

I have been tasked with integrating Azure Active Directory Authorization into one of our applications and have tried out some of the samples with relative success.
I have a Javascript SPA application (GoogleWebToolkit) that communicates with a Spring REST (not Boot) API. The Rest API is currently secured with Spring Security and login URL username/password etc.
I want to change this to use Azure OAuth2.
Being new to OAuth2 I'm trying to figure out if I should be using either of the following Spring options.
With this option all the configuration is done at the server side, client id,secret
If I do a href from the SPA front end to 'oauth2/authorization/AzureAD' URL, its sends a redirect to the Azure Login page, allows authentication and redirects back to what redirect URL I enter into the Azure AD console configuration. This works to a degree but trying to extract the token and pass it back is not working so far.
http.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService())
.authorizationEndpoint()
.authorizationRequestResolver(
new CustomAuthorizationRequestResolver(
clientRegistrationRepository(),
#Bean
public ClientRegistration clientRegistration() {
ClientRegistration.Builder builder = ClientRegistration.withRegistrationId("AzureAD");
builder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
........................
or
I haven't fully tried this option yet, but I think it involves doing the authorization directly from the SPA javascript front end, put all the values for the client id/secret into the javascript FE etc, and then passing the once acquired token via the Auth header for validation by the server side. Like at https://www.baeldung.com/spring-security-oauth-jwt
.oauth2ResourceServer()
.jwt()
.jwkSetUri("https://login.microsoftonline.com/common/discovery/v2.0/keys");
Could someone confirm where I should be using Option 1 or 2, and if I am understanding things properly?
Your understanding is correct in option 2. As per above scenario, let’s consider Front End Application which is Single Page Application (Java Script) to be OAuth Client App to orchestrate the process of obtaining access token and then grant access to resources from Spring back-end application.
So, here client Application need to be registered in Azure AD to acquire the access token secured by Azure AD.
We recommended MSAL libraries which helps to acquire tokens from the Microsoft identity platform and handle token in many ways to authenticate users and access secured web APIs.
Both the applications (front end and back end) need to register in Azure AD based on the scenario.
Update client-id, tenant-id, redirect URI to front end application configuration file based on application registration in Azure AD.
Back-end application also need to be registered in Azure Ad to secure by Microsoft Identity which can then define the delegated permissions(scopes) your API exposes.
Then business logic needs to add in back-end application to determine what is allowed or prohibited based on these scopes in access token.
To authorize the client request in Spring application:
Users will start by authenticating with a username and password in front end application.
Once authenticated, the client will receive a JWT representing an access token.
The client will include the access token in the authorization header of every request to a secure endpoint.
The resource server will validate the access token and determine if it has the right permissions, using the information within the token.
In this case, Spring serves as resource server and not acquiring any token in the back-end application .
Security Configuration in Spring provides numerous methods to add filters to the HTTP request to authenticate each request.
Here,
http.cors() will allows Cross-Origin Resource Sharing (CORS) checks to succeed.
All the requests need to authenticate before passing to the application(controllers).
Spring application serve as a resource server and authentication should be provided via JWT access tokens and further validate the roles and scopes in the application’s controller using #AllowedRoles annotation.
Our JWT access tokens are signed by Azure AD and application should check if their signature is correct. Azure AD has an endpoint with the public key to do so, which need to configure in spring application.
Also, as mentioned, we will need access token to call the protected back-end application because contents of the token are intended for the resource (back-end API) to perform authentication and authorization.
To validate the token, you can search the keys endpoint in the discovery document and then provide this JSON web key (JWK) endpoint straight away where JWK URI can be found.
# application.properties
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://login.windows.net/common/discovery/keys
Note: The flow would be same to get the access token while integrating with Azure AD. i.e in Spring boot or in spring.

How to use Azure AD access_token and id_token

I have registered two applications in Azure AD, a .Net core web API and a single page react application. I configured these applications to get the id_token for the react client application and an access token for consuming the web API when the user signs in to the client application. I need to send user-specific information to my API when the user signs in (I need to get a unique id from the token to identify the user). Some document says we can't send the id_token to the API since it is issued for the client application. and some says we can't send the user-specific information via access token since it should be used for authorization purpose only.
Is there any other way to solve my problem?
In the context of Open Id connect, is it ok to send user-specific information via access token? I want a unique id from the token and store it in my system to identify the user. if it is ok to use the access token, Which claim is best suited for this purpose (sub or oid)?
You are right that you should not send the id_token to the API. One option is to include the necessary user information as claims inside the access token. Alternatively you could try to ask AzureAD for the user details when the API receives the access token. Azure for example provides the UserInfo endpoint for this.
See this page Microsoft identity platform UserInfo endpoint

Refresh token flow in Azure Active Directory with a federated Google user

I have set up an Azure Active Directory tenant with direct federation to Google. Next to that I have a .NET core web application using the OIDC code flow for getting both id_tokens and access and refresh tokens. The access token is used to call my API which is working fine.
Now the problem is whenever I use my refresh_token to get a new access_token I receive a new access_token, but no refresh_token. So I can only refresh once.
I only have this issue when authenticating with my Google account using direct federation. When I authenticate using a tenant native account I can refresh unlimited.
We have two multitenant Azure AD app registrations as described here. One for our single page application and one for our API. In our single page application backend we use the OpenIdConnect middleware to authenticate against Azure AD. Note that we are not using the common endpoint, but the tenant specific endpoint because otherwise direct federation does not work. We can reproduce this issue by intercepting the refresh token in the OnTokenResponseReceived event of the OIDC middleware and initiating the refresh flow as stated here (by using Postman for instance). The response is successful, but does only contain an access token, no refresh token.
Is this behavior by design?

Is Azure OAuth 2 auth code grant an authentication protocol

Sorry I am still very confused, read everywhere telling me oath is a authorisation protocol but it appears using the azure ad oauth code grant, it does promote a login screen to authenticate against the directory, so is it not an authentication process? what is the relationship between the open id connect? thanks!!
the OAuth2.0 protocol has several flows that an identity provider (in your case Azure AD) may implement to support auth.
The Auth Code flow is in fact one of these used by apps to get access tokens for some api. The flow is quite simple, an app redirects the user to the identity providers /authorize endpoint. At this point the user enters their credentials, and the site redirects back to your application with an authorization code and can also issue an ID Token that represents a user (This is the OpenID Connect part). The app takes this code, and POSTs it to the /token endpoint and will be issued an access token and refresh token. With the access token, your app can access whatever api you've requested access for.
For Azure AD specifically, Microsoft has built libraries that handle all these flows and token caching so most of the complexity is abstracted away. There's some simple code samples that you can checkout that you may find helpful. The authentication protocols and scenarios doc for Azure AD may also be really helpful for conceptual information.

Resources