c# - OAuth2 身份验证失败.net 核心 api 调用在 React-Typescript Web 应用程序上使用 Msal.js 失败

标签 c# typescript oauth-2.0 azure-active-directory msal

我有一个客户端 Typescript React Web 应用程序需要与 .net 核心 api 进行通信。在客户端集成了 msal.js。我能够登录 AAD,获取用户帐户和访问 token 并将其作为 Bearer 传递给 api 调用。但是 api 级别的身份验证失败。

在客户端:

config: Msal.Configuration = buildConfiguration({ auth: {
        clientId: 'clientId',
        authority: 'authority',
        validateAuthority: true,
        navigateToLoginRequestUrl: false
    } });

 request = {
        scopes: ["user.read"] 
     };

    userAgentApp : Msal.UserAgentApplication = new Msal.UserAgentApplication(this.config);

private _accessToken: string = '';
    public async GetAccessToken(): Promise<string>{
        if(this._accessToken == '')
        {
            await this.userAgentApp.acquireTokenSilent(this.request)
                .then((tokenResponse) => this._accessToken = tokenResponse.accessToken)
                .catch((error) => console.log(error))
        }

        return this._accessToken;
    }

    public login() {
        console.log("before login");

        this.userAgentApp.handleRedirectCallback((error, response) => 
        { 
            console.error(error)
        });

        this.userAgentApp.loginRedirect(this.request);

        console.log("after login")
    }

// Calling the api
  axios.defaults.headers.common = {'Authorization': `Bearer ${accessToken}`}
      const travelExpensesResponse = await axios.get("https://localhost:44350/api/reisekostenantrag")

在 API 上


// Start.cs ConfigureServices
  services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
 .AddJwtBearer(options =>
            {
                options.Audience = "clientId";
                options.Authority = "authority";
            });

我遇到了 SecurityTokenInvalidSignatureException:IDX10511:签名验证失败。

  1. 问题出在哪里?
  2. 是否有任何示例可以说明如何从客户端应用程序向 .net core api 传递 token ?

最佳答案

问题是 token 被赋予了这个范围user.read,这是一个 Graph API 范围。

所以解决方案是在 azure 中注册服务器应用程序并创建一个 custom scope .

然后在客户端应用上:


 request = {
        scopes: ["api://clientid/access_as_user"] 
     };

关于c# - OAuth2 身份验证失败.net 核心 api 调用在 React-Typescript Web 应用程序上使用 Msal.js 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935160/

相关文章:

c# - 如何在窗体上加倍缓冲 .NET 控件?

c# - 如何查找 Windows 窗体面板中是否存在标签

c# - 新的 C# 异步功能是否在编译器中严格实现

javascript - 从 json 对象初始化 Typescript 中的 Map<string,string>

javascript - 枚举成员如何在 TypeScript 中使用别名?

javascript - 使用自定义 header 重定向到外部站点 - AngularJS/OAuth

java - 无法找到 token 的访问 token

architecture - "OAuth Provider"究竟是什么?

c# - 如何将图像保存在数据库中并将其显示到 MVC 4 中的 View 中?

javascript - React useRef 当前不是每次都更新