简体   繁体   中英

Client - API authentication flow with Microsoft Azure AD

I'm building a react frontend application with a spring backend that is secured with azure ad.

I can't get the authentication flow to work.

In azure ad, I have registered 2 applictions:

  1. API: Default configurations and under "Expose an API" I have added a scope with api://xxxx-api/Access.Api and also added the client application. Under "App Roles" I have added the roles "User" and "Admin". I have assignes both roles to myself.
  2. Client: Registered as SPA with redirect to http://localhost:3000 where the react app is running. Did not check the two boxes for the token to enable PKCE. Under "API permissions" I added the "Access.Api" scope from the api app and granted admin consent.

In the react app I'm using @azure/msal-browser and @azure/msal-react .

My authConfig looks like this: 在此处输入图像描述

Then I'm just using useMsalAuthentication(InteractionType.Popup); to sign the user in.

All this works as expected and I'm getting a token back. If I parse this token in jwt.io , I get "iss": "https://sts.windows.net/42xxxxx-xxxxx-xxxxxx-xxxxx/" , "scp": "openid profile User.Read email" , "ver": "1.0", .

However, I do not see the scopes or roles for my API app.

I'm then using an Axios request interceptor to provide the bearer token on every API request:

const { instance, accounts } = useMsal();
const account = useAccount(accounts[0]);

axios.interceptors.request.use(async (config) => {
    if (!account) {
        throw Error('No active account! Verify a user has been signed in.');
    }
    const response = await instance.acquireTokenSilent({
        ...loginRequest,
        account,
    });
    config.headers.Authorization = `Bearer ${response.accessToken}`;

    return config;
});

The token is successfully added to the header of each request.

My spring application however fails to validate this token. 在此处输入图像描述

My spring config:

在此处输入图像描述

在此处输入图像描述

I could implement the token validation myself if that is an issue here, but how do I fix, that the bearer token does not contain the roles that I need to check if the user has access to specific resources on the api?

I figured it out.

Basically the scopes openid , email and profile should only be used when requesting an ID token. The ID token contains all roles exposed in the client app.

If these scopes are used when requesting an access token, the token will contain no roles or scopes at all. Only use the scope from the api app that is exposed in the client app when requesting an access token, and the roles will show up in the access token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM