Azure Active Directory - 存储访问令牌的 MVC 应用程序最佳实践

2024-07-04

我使用 Azure Active Directory (AAD) 设置了一个简单的 MVC 应用程序。

我需要查询 AAD Graph API 才能从我的应用程序管理应用程序角色和组。

In the Startup类中,我收到了这样的 AccessToken:

public void ConfigureAuth(IAppBuilder app)
{
    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = Constants.ClientId,
            Authority = Constants.Authority,
            PostLogoutRedirectUri = Constants.PostLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                AuthorizationCodeReceived = (context) =>
                {
                    var code = context.Code;
                    var credential = new ClientCredential(Constants.ClientId, Constants.ClientSecret);
                    var signedInUserId =
                        context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    var authContext = new AuthenticationContext(Constants.Authority,
                        new TokenDbCache(signedInUserId));
                    var result = authContext.AcquireTokenByAuthorizationCode(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential,
                        Constants.GraphUrl);

                    var accessToken = result.AccessToken;                        
                    return Task.FromResult(0);
                }
            }
        });
}

实例化ActiveDirectoryClient类,我需要传递 AccessToken :

var servicePointUri = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(servicePointUri, tenantID);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
        async () => await GetTokenForApplication());

我想知道将 AccessToken 存储为声明是否是一个好的解决方案(在Startup class)?

context.AuthenticationTicket.Identity.AddClaim(new 
    Claim("OpenId_AccessToken", result.AccessToken));

编辑令牌已存储..

得到它 !!!谢谢乔治。 所以我的令牌已使用以下方式存储在数据库中TokenDbCache class.

根据示例再次获取它(在我的控制器之一中):

public async Task<string> GetTokenForApplication()
{
    string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
    string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

    // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
    ClientCredential clientcred = new ClientCredential(clientId, appKey);
    // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
    AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new TokenDbCache<ApplicationDbContext>(signedInUserID));
    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    return authenticationResult.AccessToken;
}

我不知道的是AuthenticationContext: 如果已经请求了令牌,它将从TokenDbCache.


当您通过 Adal 检索令牌时,它会将其缓存在 NaiveCache 对象中。

使用 StartUp 类检索令牌的代码:

  AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, "Your API Resource ID");
                            string kdAccessToken = kdAPiresult.AccessToken;

在 Azure Active Directory 示例中(https://github.com/AzureADSamples https://github.com/AzureADSamples)此对象用于在应用程序控制器中检索令牌。您可以实现自己的缓存,以相同的方式检索它。

在您的控制器代码中,您可以执行以下操作:

IOwinContext owinContext = HttpContext.GetOwinContext();
                string userObjectID = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
                NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, cache);
                TokenCacheItem kdAPITokenCache = authContext.TokenCache.ReadItems().Where(c => c.Resource == "You API Resource ID").FirstOrDefault();

如果您不是通过 AuthenticationContext(3d 方 api)获取令牌,您也可以将令牌存储在声明中

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Azure Active Directory - 存储访问令牌的 MVC 应用程序最佳实践 的相关文章

随机推荐

  • 用于 LIKE 时 MySqli 准备语句错误

    我正在尝试使用 php 的 mysqli 扩展为 LIKE 查询制作准备好的语句 但无论我尝试什么 我总是会收到此错误 Fatal error Problem preparing query SELECT f r slug FROM foo
  • ASP.net 和 PHP 之间的根本区别是什么? [复制]

    这个问题在这里已经有答案了 可能的重复 NET 和 ASP 与 PHP https stackoverflow com questions 606419 net asp vs php 是否存在速度差异 性能问题 企业选择其中一种的原因是什么
  • Scipy 多元正态:如何绘制确定性样本?

    我在用Scipy stats multivariate normal https docs scipy org doc scipy 0 14 0 reference generated scipy stats multivariate no
  • $.ajax - 数据类型

    有什么区别 contentType application json charset utf 8 dataType json vs contentType application json dataType text contentType
  • 如何在水晶报表图表中显示月份名称?

    我正在使用 Crystal Report 2008 在折线图中 我想在报告的 x 轴上显示月份名称 例如 Jan Feb March 如何在 x 轴上显示月份 执行此操作的最佳方法是使用以下公式创建一个单独的公式字段 cstr monthn
  • PHP 插入数组值、表名

    我正在努力处理 PHP 插入语句 我希望它通过使用将数据插入数据库array keys values and array values values 我试图弄清楚如何做到这一点 到目前为止 我的插入中已包含此代码 并且还包含了我的索引页 我
  • 使用Redis缓存SQL结果

    我有一个基于 SQL 的应用程序 我喜欢使用 Redis 缓存结果 您可以将该应用程序视为具有多个 SQL 表的地址簿 该应用程序执行以下任务 40 的时间 创建新记录 更新现有记录 批量更新多条记录 查看现有记录 60 的时间 根据用户的
  • 如何防止在angularjs中的数组推送中出现重复

    我的代码是这样的 var arr arr push item1 item2 so arr将包含类似 名称 事物1 但是当我推送具有相同精确值的元素时遇到问题 如何过滤相同的元素值但仍然接受更新 更改 JSFIDDLE http jsfidd
  • Mule 从 JBoss 发出 http 请求时出错

    我有一个 Mule 流正在尝试发出出站 HTTP 请求
  • 将文件从控制台应用程序上传到 WebAPI

    我正在尝试将文件 一些信息发布到我控制的WebApi 我的问题是我无法访问 WebAPI 端的文件 所有其他字段都正常 这是我的控制台应用程序代码 using HttpClient client new HttpClient using M
  • Udacity Web Python 解释器如何工作?

    Udacity http www udacity com 为学生提供一个网络编辑器来输入 Python 程序 该编辑器可识别 Python 关键字和内置函数 并允许运行程序 你知道这项技术是如何运作的吗 程序是提交到后端并由标准 Pytho
  • 奇怪的图表最大轴x值(真正的挑战)

    在这里您可以看到使用 graphael 创建的图表 http jsfiddle net aNJxf 4 http jsfiddle net aNJxf 4 它的 y 轴正确显示 第一个 y 值为 0 03100 y 轴的最大值为 0 031
  • 错误:添加显式大括号以避免其他内容悬空。 C

    我正在使用 gedit 我的编译器是 clang 我最近遇到了一些这样的错误 但不知道如何修复 标题中的错误并引用了 else 语句 if isupper ptext i if ptext i k 26 52 lt 65 ptext i k
  • 使用 NSURLConnection 进行单元测试

    我想测试一段使用网络的代码 NSURLConnection类 具体而言 代码 我们称之为NetworkManager 看起来有点像这样 id buildConnection some more code and then return NS
  • Scrapy + Splash = 连接被拒绝

    我安装了Splash使用这个link http splash readthedocs io en stable install html 按照所有步骤进行安装 但 Splash 不起作用 My 设置 py file BOT NAME Tes
  • Cocoa:如何制作像 Pages 或 Numbers 中那样的小工具栏?

    Apple 的应用程序 例如 Pages 和 Numbers 总是在主工具栏下方显示一个附加的小工具栏 Interface Builder 中是否有这样的对象 或者我必须从头开始构建它 我查了一下 IB 图书馆 但到目前为止什么也没找到 您
  • Get-Content -wait 无法按照文档中的描述工作

    我注意到当Get Content path to logfile Wait 输出实际上并不是像文档所解释的那样每秒刷新一次 如果我进入 Windows 资源管理器到日志文件所在的文件夹并刷新该文件夹 然后Get Content会将最新更改输
  • 子表 ajax 调用内的 SelectOneRadio 不起作用

    我正在使用 primefaces 3 4 1 并且我正在尝试使用 SelectOneRadio 和 ajax 调用subtable http www primefaces org showcase labs ui datatableSubT
  • 写入文件并处理重复条目

    背景 1 个按钮 1 需要写入的文件 1 个文本框 1 数字上下 因此 在我的应用程序中 我需要写入一个包含多行的文件 输入取自 TextBox 和 NumericUpDown 控件 它包含通用格式的字符串string Format 0 1
  • Azure Active Directory - 存储访问令牌的 MVC 应用程序最佳实践

    我使用 Azure Active Directory AAD 设置了一个简单的 MVC 应用程序 我需要查询 AAD Graph API 才能从我的应用程序管理应用程序角色和组 In the Startup类中 我收到了这样的 Access