pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

.Net Core 2.0 - 獲取 AAD 訪問(wèn)令牌以與 Microsoft Graph

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

問(wèn)題描述

限時(shí)送ChatGPT賬號(hào)..

使用 Azure AD 身份驗(yàn)證啟動(dòng)新的 .Net Core 2.0 項(xiàng)目時(shí),您會(huì)獲得一個(gè)可以登錄租戶的工作示例,太棒了!

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!

現(xiàn)在我想獲取已登錄用戶的訪問(wèn)令牌,并使用它與 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.

我沒(méi)有找到任何關(guān)于如何實(shí)現(xiàn)這一點(diǎn)的文檔.我只想要一種簡(jiǎn)單的方法來(lái)獲取訪問(wèn)令牌并訪問(wèn)圖形 API,使用啟動(dòng)新 .NET Core 2.0 項(xiàng)目時(shí)創(chuàng)建的模板.從那里我應(yīng)該能夠弄清楚其余的.

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 中創(chuàng)建新的 2.0 MVC Core 應(yīng)用程序時(shí),它適用于在執(zhí)行選擇工作和學(xué)校帳戶進(jìn)行身份驗(yàn)證的過(guò)程時(shí)創(chuàng)建的項(xiàng)目.

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.

推薦答案

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

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

TL;DR 是當(dāng)您收到來(lái)自 AAD 的授權(quán)代碼時(shí),您應(yīng)該添加這樣的處理程序:

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),我從配置和其他設(shè)置綁定(客戶 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 兌換令牌,并將生成的令牌存儲(chǔ)在令牌緩存中.

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

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

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;
        }
    }
}

這里的令牌緩存使用分布式緩存來(lái)存儲(chǔ)令牌,以便為您的應(yīng)用提供服務(wù)的所有實(shí)例都可以訪問(wèn)令牌.它們按用戶緩存,因此您可以稍后為任何用戶檢索令牌.

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.

然后,當(dāng)您想要獲取令牌并使用 MS 圖時(shí),您會(huì)執(zhí)行類似(GetAccessTokenAsync() 中的重要內(nèi)容):

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;
    }
}

我們?cè)诖颂庫(kù)o默獲取令牌(使用令牌緩存),并將其附加到對(duì) Graph 的請(qǐng)求中.

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

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

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

相關(guān)文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進(jìn)行身份驗(yàn)證并跨請(qǐng)求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權(quán)不起作用)
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(如何獲取守護(hù)進(jìn)程或服務(wù)器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問(wèn)令牌和刷新令牌) - IT屋-程序員軟件開(kāi)發(fā)技
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調(diào)用時(shí) Azure KeyVault Active Directory AcquireTokenAsync 超時(shí))
Getting access token using email address and app password from oauth2/token(使用電子郵件地址和應(yīng)用程序密碼從 oauth2/token 獲取訪問(wèn)令牌)
主站蜘蛛池模板: 活性炭-果壳木质煤质柱状粉状蜂窝活性炭厂家价格多少钱 | 重庆钣金加工厂家首页-专业定做监控电视墙_操作台 | 新密高铝耐火砖,轻质保温砖价格,浇注料厂家直销-郑州荣盛窑炉耐火材料有限公司 | Brotu | 关注AI,Web3.0,VR/AR,GPT,元宇宙区块链数字产业 | 西门子代理商_西门子变频器总代理-翰粤百科 | 杭州中策电线|中策电缆|中策电线|杭州中策电缆|杭州中策电缆永通集团有限公司 | 方源木业官网-四川木门-全国木门专业品牌 | 送料机_高速冲床送料机_NC伺服滚轮送料机厂家-东莞市久谐自动化设备有限公司 | 烘箱-工业烘箱-工业电炉-实验室干燥箱 - 苏州华洁烘箱制造有限公司 | elisa试剂盒价格-酶联免疫试剂盒-猪elisa试剂盒-上海恒远生物科技有限公司 | 利浦顿蒸汽发生器厂家-电蒸汽发生器/燃气蒸汽发生器_湖北利浦顿热能科技有限公司官网 | 哈希PC1R1A,哈希CA9300,哈希SC4500-上海鑫嵩实业有限公司 | 空冷器|空气冷却器|空水冷却器-无锡赛迪森机械有限公司[官网] | 超细|超微气流粉碎机|气流磨|气流分级机|粉体改性机|磨粉机|粉碎设备-山东埃尔派粉体科技 | 篷房[仓储-婚庆-展览-活动]生产厂家-江苏正德装配式帐篷有限公司 | 包装盒厂家_纸盒印刷_礼品盒定制-济南恒印包装有限公司 | 电动卫生级调节阀,电动防爆球阀,电动软密封蝶阀,气动高压球阀,气动对夹蝶阀,气动V型调节球阀-上海川沪阀门有限公司 | 贴片电容代理-三星电容-村田电容-风华电容-国巨电容-深圳市昂洋科技有限公司 | 超声骨密度仪-骨密度检测仪-经颅多普勒-tcd仪_南京科进实业有限公司 | 能耗监测系统-节能监测系统-能源管理系统-三水智能化 | 北京签证代办_签证办理_商务签证_旅游签证_寰球签证网 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 | 成人纸尿裤,成人尿不湿,成人护理垫-山东康舜日用品有限公司 | 清洁设备_洗地机/扫地机厂家_全自动洗地机_橙犀清洁设备官网 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 智能终端_RTU_dcm_北斗星空自动化科技| 儿童乐园|游乐场|淘气堡招商加盟|室内儿童游乐园配套设备|生产厂家|开心哈乐儿童乐园 | 基业箱_环网柜_配电柜厂家_开关柜厂家_开关断路器-东莞基业电气设备有限公司 | 郑州巴特熔体泵有限公司专业的熔体泵,熔体齿轮泵与换网器生产厂家 | HEYL硬度计量泵-荧光法在线溶解氧仪-净时测控技术(上海)有限公司 | 中医治疗皮肤病_潍坊银康医院「山东」重症皮肤病救治平台 | 京港视通报道-质量走进大江南北-京港视通传媒[北京]有限公司 | 扒渣机厂家_扒渣机价格_矿用扒渣机_铣挖机_撬毛台车_襄阳永力通扒渣机公司 | 西安微信朋友圈广告投放_微信朋友圈推广_西安度娘网络科技有限公司 | 雨燕360体育免费直播_雨燕360免费NBA直播_NBA篮球高清直播无插件-雨燕360体育直播 | 内六角扳手「厂家」-温州市威豪五金工具有限公司 | 南京租车,南京汽车租赁,南京包车,南京会议租车-南京七熹租车 | 瓶盖扭矩仪(扭力值检测)-百科| 304不锈钢无缝管_不锈钢管厂家 - 隆达钢业集团有限公司 | 淋巴细胞分离液_口腔医疗器材-精欣华医疗器械(无锡)有限公司 | 臭氧实验装置_实验室臭氧发生器-北京同林臭氧装置网 |