使用Azure AD MSAL进行React / .Net核心身份验证

时间:2019-09-13 14:41:10

标签: .net reactjs .net-core azure-active-directory

我有一个React前端,它使用最新版本的react-aad-msal向Azure AD进行身份验证,它的这一部分工作正常。我现在想要实现的是通过从前端发送承载令牌来将.NET Core API保护到同一Azure AD。我有此设置,并且对前端的身份验证工作正常。我可以在最新版本的react-aad-msal中获得访问令牌,但是当我将其发送到API时,总是会收到“无效令牌”错误。我不确定我使用的范围是否不正确,或者访问令牌是否不是发送令牌的正确类型?这是代码:

API:

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
...
app.UseAuthentication();

反应应用程序:

ReactDOM.render(
<AzureAD provider={authProvider} reduxStore={basicReduxStore}>
    {({login, logout, authenticationState}) => {
        if (authenticationState === AuthenticationState.Authenticated) {

authProvider的配置如下:

config = {
    auth: {
        authority: 'https://login.microsoftonline.com/<mytenantidhere>',
        clientId: <clientidhere>,
        redirectUri: 'http://localhost:3000'
    },
    cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: true
    }
};

export const msalConfig = config;
export const authParams = {
scopes: [
    'https://graph.microsoft.com/User.ReadBasic.All',
    'https://graph.microsoft.com/profile',
    'https://graph.microsoft.com/User.Read'
]
};

用户通过身份验证后,我想从API获取一些其他信息,例如:

const token = await authProvider.getAccessToken();
    context.token = token;

    axios
        .get('Employees/getCurrentEmployee', {
            headers: {
                'Authorization': "Bearer " + token.accessToken
            }
        })
        .then(response => {
            context.user = response.data;
        });

我可以像这样验证令牌是否位于标题中:

授权
承载eyJ0eXAiOiJKV1QiLCJub25…8Wt1C6ni32UZUwV-53hp53jxHG38w

但是收到此错误:

bearer error =“ invalid_token”,error_description =“签名无效”

1 个答案:

答案 0 :(得分:1)

您将获得MS Graph的访问令牌。您的Web API不是Graph,因此预期它将拒绝令牌。

您要做的是为Web API创建范围(在Azure门户>您的API> 公开API 中)。然后在 API权限菜单标签上的客户端应用上对其进行配置。然后将其添加到您的范围集合:

export const authParams = {
scopes: [
    'https://graph.microsoft.com/User.ReadBasic.All',
    'https://graph.microsoft.com/profile',
    'https://graph.microsoft.com/User.Read',
    'https://myWebApiUri/MyScope',
]
};