【问题标题】:React/.Net Core Authentication with Azure AD MSAL使用 Azure AD MSAL 进行 React/.Net Core 身份验证
【发布时间】:2019-09-14 05:51:27
【问题描述】:

我有一个 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="签名无效"

【问题讨论】:

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


【解决方案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',
]
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多