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)令牌)
主站蜘蛛池模板: 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | 精密模具加工制造 - 富东懿 | 恒温油槽-恒温水槽-低温恒温槽厂家-宁波科麦仪器有限公司 | 商秀—企业短视频代运营_抖音企业号托管 | 不锈钢/气体/液体玻璃转子流量计(防腐,选型,规格)-常州天晟热工仪表有限公司【官网】 | 电动车头盔厂家_赠品头盔_安全帽批发_山东摩托车头盔—临沂承福头盔 | 哲力实业_专注汽车涂料汽车漆研发生产_汽车漆|修补油漆品牌厂家 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | 首页_中夏易经起名网| 蒸汽热收缩机_蒸汽发生器_塑封机_包膜机_封切收缩机_热收缩包装机_真空机_全自动打包机_捆扎机_封箱机-东莞市中堡智能科技有限公司 | 欧必特空气能-商用空气能热水工程,空气能热水器,超低温空气源热泵生产厂家-湖南欧必特空气能公司 | 室内室外厚型|超薄型|非膨胀型钢结构防火涂料_隧道专用防火涂料厂家|电话|价格|批发|施工 | 广州二手电缆线回收,旧电缆回收,广州铜线回收-广东益福电缆线回收公司 | 361°官方网站 | KBX-220倾斜开关|KBW-220P/L跑偏开关|拉绳开关|DHJY-I隔爆打滑开关|溜槽堵塞开关|欠速开关|声光报警器-山东卓信有限公司 | 专业生物有机肥造粒机,粉状有机肥生产线,槽式翻堆机厂家-郑州华之强重工科技有限公司 | 环氧树脂地坪_防静电地坪漆_环氧地坪漆涂料厂家-地壹涂料地坪漆 环球电气之家-中国专业电气电子产品行业服务网站! | LED灯杆屏_LED广告机_户外LED广告机_智慧灯杆_智慧路灯-太龙智显科技(深圳)有限公司 | 三效蒸发器_多效蒸发器价格_四效三效蒸发器厂家-青岛康景辉 | 济南保安公司加盟挂靠-亮剑国际安保服务集团总部-山东保安公司|济南保安培训学校 | 磁棒电感生产厂家-电感器厂家-电感定制-贴片功率电感供应商-棒形电感生产厂家-苏州谷景电子有限公司 | 济南电缆桥架|山东桥架-济南航丰实业有限公司 | 污水提升器,污水提升泵,地下室排水,增压泵,雨水泵,智能供排水控制器-上海智流泵业有限公司 | 高低温万能试验机_拉力试验机_拉伸试验机-馥勒仪器科技(上海)有限公司 | 自动化改造_智虎机器人_灌装机_贴标机-上海圣起包装机械 | 冷藏车-东风吸污车-纯电动环卫车-污水净化车-应急特勤保障车-程力专汽厂家-程力专用汽车股份有限公司销售二十一分公司 | DNA亲子鉴定_DNA基因检测中心官方预约平台-严选好基因网 | 天津热油泵_管道泵_天津高温热油泵-天津市金丰泰机械泵业有限公司【官方网站】 | 篮球地板厂家_舞台木地板品牌_体育运动地板厂家_凯洁地板 | 猪I型/II型胶原-五克隆合剂-细胞冻存培养基-北京博蕾德科技发展有限公司 | 房在线-免费房产管理系统软件-二手房中介房屋房源管理系统软件 | 压砖机_电动螺旋压力机_粉末成型压力机_郑州华隆机械tel_0371-60121717 | 紫外可见光分光度计-紫外分光度计-分光光度仪-屹谱仪器制造(上海)有限公司 | 铸铁平台,大理石平台专业生产厂家_河北-北重机械 | 氢氧化钾厂家直销批发-济南金昊化工有限公司 | 吉林污水处理公司,长春工业污水处理设备,净水设备-长春易洁环保科技有限公司 | 磁力加热搅拌器-多工位|大功率|数显恒温磁力搅拌器-司乐仪器官网 | 桑茶-七彩贝壳桑叶茶 长寿茶 | 贝壳粉涂料-内墙腻子-外墙腻子-山东巨野七彩贝壳漆业中心 | 光栅尺_Magnescale探规_磁栅尺_笔式位移传感器_苏州德美达 | 上海风淋室_上海风淋室厂家_上海风淋室价格_上海伯淋 | 翅片管散热器价格_钢制暖气片报价_钢制板式散热器厂家「河北冀春暖气片有限公司」 |