简体   繁体   English

如何在.net核心项目中从javascript调用microsoft graph api

[英]How to call microsoft graph api from javascript in .net core project

I have .net core project, where I need to call microsoft graph api. I already login and authenticated.我有 .net 核心项目,我需要调用 microsoft graph api。我已经登录并通过了身份验证。 But in some pages I need to fetch meeting room status and I need to call it from javascript to access token.但是在某些页面中,我需要获取会议室状态,并且需要从 javascript 调用它来访问令牌。 I am following this tutorial but it not working: https://learn.microsoft.com/en-us/graph/tutorials/javascript?tutorial-step=1我正在按照本教程进行操作,但它不起作用: https://learn.microsoft.com/en-us/graph/tutorials/javascript?tutorial-step=1

I am getting error at below lines:我在以下几行收到错误:

 try {
            authResult = await msalClient.ssoSilent(msalRequest);

        } catch (err) {

            authResult = await msalClient.loginPopup(msalRequest).catch(error => {
                // handle error
            });

        }

I assume you have an asp.net core MVC project and has integrate azure ad to let users sign in.我假设您有一个 asp.net 核心 MVC 项目,并集成了 azure 广告让用户登录。

Then it means you realized the authentication in the server side, so if you need to call graph api in your client side, then you have to generate access token in the server side and then send the token to your page.那么这意味着你在服务器端实现了身份验证,所以如果你需要在你的客户端调用graph api,那么你必须在服务器端生成访问令牌,然后将令牌发送到你的页面。 This is my idea and here my test.这是我的想法,这是我的测试。

Controller: Controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebMvcApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;

namespace WebMvcApp.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly ITokenAcquisition _tokenAcquisition;
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger, ITokenAcquisition tokenAcquisition)
        {
            _logger = logger;
            _tokenAcquisition = tokenAcquisition;
        }

        public async Task<IActionResult> IndexAsync()
        {
            string[] scopes = new string[] { "user.read" };
            string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);

            return View();
        }
    }
}

appsettings.json应用程序设置.json

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your_tenant_name.onmicrosoft.com",
    "TenantId": "tenant_id",
    "ClientId": "azure_ad_app_clientid",
    "ClientSecret": "client_secret",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc"
  }

StartUp.cs启动文件

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

public void ConfigureServices(IServiceCollection services)
{
    services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
        .AddInMemoryTokenCaches();
    services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    }).AddMicrosoftIdentityUI();
}

and pls don't forget app.UseAuthentication();请不要忘记app.UseAuthentication(); in Configure method.Configure方法中。

Then add login page _LoginPartial.cshtml and add it to layout:然后添加登录页面_LoginPartial.cshtml并将其添加到布局中:

@using System.Security.Principal

<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
        <li class="nav-item">
            <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Ajax调用获取Microsoft Graph API Access令牌 - How to get Microsoft Graph API Access token using ajax call 如何从 Javascript Microsoft Dynamics 调用操作 - How to call Actions from Javascript Microsoft Dynamics How to load javascript files after swagger UI is loaded in .net core web api project - How to load javascript files after swagger UI is loaded in .net core web api project Microsoft Graph API Javascript SDK 承诺 - Microsoft Graph API Javascript SDK Promises 获取扩展属性Microsoft graph JavaScript API - Get extended property Microsoft graph javascript api 如何在asp.net core v 2.0中从javascript调用PageModel方法 - How to call PageModel Method from javascript in asp.net core v 2.0 如何使用提取将JavaScript中的FormData发送到ASP.NET Core 2.1 Web API - How to send FormData from javascript to ASP.NET Core 2.1 web API using fetch 如何从TypeScript项目调用JavaScript库? - How to call JavaScript libraries from TypeScript project? 如何从插件中调用javascript或刷新microsoft dynamics 2015中的页面 - How to call a javascript from plugin or refresh the page in microsoft dynamics 2015 如何从JavaScript调用Google Tasks API? - How to call Google Tasks API from javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM