久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph

.Net Core 2.0 - Get AAD access token to use with Microsoft Graph(.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用)
本文介紹了.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

使用 Azure AD 身份驗證啟動新的 .Net Core 2.0 項目時,您會獲得一個可以登錄租戶的工作示例,太棒了!

When starting up a fresh .Net Core 2.0 project with Azure AD Authentication you get a working sample that can sign in to your tenant, great!

現在我想獲取已登錄用戶的訪問令牌,并使用它與 Microsoft Graph API 一起工作.

Now I want to get an access token for the signed in user and use that to work with Microsoft Graph API.

我沒有找到任何關于如何實現這一點的文檔.我只想要一種簡單的方法來獲取訪問令牌并訪問圖形 API,使用啟動新 .NET Core 2.0 項目時創建的模板.從那里我應該能夠弄清楚其余的.

I am not finding any documentation on how to achieve this. I just want a simple way to get an access token and access the graph API, using the template created when you start a new .NET Core 2.0 project. From there I should be able to figure out the rest.

在 Visual Studio 中創建新的 2.0 MVC Core 應用程序時,它適用于在執行選擇工作和學校帳戶進行身份驗證的過程時創建的項目.

Very important that it works with the project that gets created when following the process where you select Work and school accounts for authentication when creating a new 2.0 MVC Core app in Visual Studio.

推薦答案

我寫了一篇博客文章,展示了如何做到這一點:ASP.NET Core 2.0 Azure AD 身份驗證

I wrote a blog article which shows just how to do that: ASP.NET Core 2.0 Azure AD Authentication

TL;DR 是當您收到來自 AAD 的授權代碼時,您應該添加這樣的處理程序:

The TL;DR is that you should add a handler like this for when you receive an authorization code from AAD:

.AddOpenIdConnect(opts =>
{
    Configuration.GetSection("Authentication").Bind(opts);

    opts.Events = new OpenIdConnectEvents
    {
        OnAuthorizationCodeReceived = async ctx =>
        {
            var request = ctx.HttpContext.Request;
            var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
            string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            var cache = new AdalDistributedTokenCache(distributedCache, userId);

            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource);

            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
    };
});

這里我的 context.Options.Resourcehttps://graph.microsoft.com (Microsoft Graph),我從配置和其他設置綁定(客戶 ID 等).

Here my context.Options.Resource is https://graph.microsoft.com (Microsoft Graph), which I'm binding from config along with other settings (client id etc.).

我們使用 ADAL 兌換令牌,并將生成的令牌存儲在令牌緩存中.

We redeem a token using ADAL, and store the resulting token in a token cache.

令牌緩存是你必須要做的事情,這是示例應用程序中的示例:

The token cache is something you will have to make, here is the example from the example app:

public class AdalDistributedTokenCache : TokenCache
{
    private readonly IDistributedCache _cache;
    private readonly string _userId;

    public AdalDistributedTokenCache(IDistributedCache cache, string userId)
    {
        _cache = cache;
        _userId = userId;
        BeforeAccess = BeforeAccessNotification;
        AfterAccess = AfterAccessNotification;
    }

    private string GetCacheKey()
    {
        return $"{_userId}_TokenCache";
    }

    private void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        Deserialize(_cache.Get(GetCacheKey()));
    }

    private void AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        if (HasStateChanged)
        {
            _cache.Set(GetCacheKey(), Serialize(), new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
            });
            HasStateChanged = false;
        }
    }
}

這里的令牌緩存使用分布式緩存來存儲令牌,以便為您的應用提供服務的所有實例都可以訪問令牌.它們按用戶緩存,因此您可以稍后為任何用戶檢索令牌.

The token cache here uses a distributed cache to store tokens, so that all instances serving your app have access to the tokens. They are cached per user, so you can retrieve a token for any user later.

然后,當您想要獲取令牌并使用 MS 圖時,您會執行類似(GetAccessTokenAsync() 中的重要內容):

Then when you want to get a token and use MS graph, you'd do something like (important stuff in GetAccessTokenAsync()):

[Authorize]
public class HomeController : Controller
{
    private static readonly HttpClient Client = new HttpClient();
    private readonly IDistributedCache _cache;
    private readonly IConfiguration _config;

    public HomeController(IDistributedCache cache, IConfiguration config)
    {
        _cache = cache;
        _config = config;
    }

    [AllowAnonymous]
    public IActionResult Index()
    {
        return View();
    }

    public async Task<IActionResult> MsGraph()
    {
        HttpResponseMessage res = await QueryGraphAsync("/me");

        ViewBag.GraphResponse = await res.Content.ReadAsStringAsync();

        return View();
    }

    private async Task<HttpResponseMessage> QueryGraphAsync(string relativeUrl)
    {
        var req = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0" + relativeUrl);

        string accessToken = await GetAccessTokenAsync();
        req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        return await Client.SendAsync(req);
    }

    private async Task<string> GetAccessTokenAsync()
    {
        string authority = _config["Authentication:Authority"];

        string userId = User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        var cache = new AdalDistributedTokenCache(_cache, userId);

        var authContext = new AuthenticationContext(authority, cache);

        string clientId = _config["Authentication:ClientId"];
        string clientSecret = _config["Authentication:ClientSecret"];
        var credential = new ClientCredential(clientId, clientSecret);

        var result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userId, UserIdentifierType.UniqueId));

        return result.AccessToken;
    }
}

我們在此處靜默獲取令牌(使用令牌緩存),并將其附加到對 Graph 的請求中.

There we acquire a token silently (using the token cache), and attach it to requests to the Graph.

這篇關于.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
ASP Core Azure Active Directory Login use roles(ASP Core Azure Active Directory 登錄使用角色)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發技
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
Getting access token using email address and app password from oauth2/token(使用電子郵件地址和應用程序密碼從 oauth2/token 獲取訪問令牌)
主站蜘蛛池模板: 91福利网址| 日韩欧美网 | 久草视频在线看 | 狼人伊人影院 | 亚洲一区在线日韩在线深爱 | 国产精品成人一区二区三区 | 最新av中文字幕 | 国产精品亚洲一区二区三区在线观看 | 欧洲亚洲一区二区三区 | 狠狠撸在线视频 | 欧美日韩国产在线观看 | 亚洲精品电影网在线观看 | 黄 色 毛片免费 | 无码日韩精品一区二区免费 | 亚洲精品乱 | 二区在线观看 | 天天色图 | 九九亚洲精品 | 97精品国产一区二区三区 | 在线观看精品 | 日韩高清中文字幕 | 亚洲精品久久久久久久久久久久久 | 日本亚洲欧美 | 国产目拍亚洲精品99久久精品 | 九色网址 | 91黄在线观看 | 成人免费观看男女羞羞视频 | 毛片高清 | 99日韩 | 91免费版在线 | 中文精品一区二区 | 超碰在线播 | 国产区在线观看 | 99热这里都是精品 | a在线免费观看视频 | 色婷婷激情综合 | 91久久久久久久久久久 | 国产电影一区二区 | 欧美成人免费在线视频 | 欧美精品成人 | 免费在线观看av网址 |