繁体   English   中英

使用委托身份验证获取不记名令牌

[英]Get bearer token using delegated authentication

参考这篇文章Authorization Request 如果我的应用程序用户已经登录,我如何使用 SDK 或此 API 参考请求获取我的个人资料: https://graph.microsoft.com/v1.0/me/

SDK 我写的代码:

public async Task<string> GetFullNameAsync()
    {
        try
        {
            var user = await _client.Me
                .Request()
                .Select(data => data.DisplayName)
                .GetAsync();
            return user.DisplayName;
        }
        catch (Exception ex)
        {
            return "404 Not Found";
        }
    }

为此,如上文所述,如何使用 Web 应用程序和 .NET 核心中的单租户的委托身份验证获取不记名令牌字符串?

要使用委托身份验证获取不记名令牌,如果有帮助,请检查以下内容:

  • 利用Microsoft.Identity.Web.MicrosoftGraph nuget package 从 ASP..NET Core web 应用程序中实现图形 API。
  • 应用程序身份验证和授权在 Startup class 中设置。
  • 对于委托用户访问令牌,请使用AddMicrosoftIdentityWebApiAuthentication方法,如下示例代码所示:
public void ConfigureServices(IServiceCollection services)  
{  
services.AddHttpClient();  
services.AddScoped<GraphApiClientDirect>();  
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)  
.EnableTokenAcquisitionToCallDownstreamApi()  
.AddInMemoryTokenCaches();  
services.AddControllers(options =>  
{  
var policy = new AuthorizationPolicyBuilder()  
.RequireAuthenticatedUser()  
.Build();  
options.Filters.Add(new AuthorizeFilter(policy));  
});  
}  
  • 使用GetAccessTokenForUserAsync方法获取所需范围的新委托访问令牌。
  • 然后可以在使用Microsoft.Identity.Web包保护的 API 中使用Graph API 客户端服务
[Authorize]  
[ApiController]  
[Route("[controller]")]  
public class GraphCallsController : ControllerBase  
{  
private readonly GraphApiClientDirect _graphApiClientDirect;  
  
public GraphCallsController(GraphApiClientDirect graphApiClientDirect)  
{  
_graphApiClientDirect = graphApiClientDirect;  
}  
[HttpGet]  
public async Task<string> Get()  
{  
var user = await _graphApiClientDirect.GetGraphApiUser()  
.ConfigureAwait(false);  
return user.DisplayName;  
}  
}  
  • 在 ASP.NET 核心应用程序中使用 Graph API 客户端时,必须使用正确的初始化来获取委托访问用户访问令牌。
  • 使用IHttpClientFactory创建 HttpClient 实例来创建实例。
  • 使用ITokenAcquisition和 IHttpClientFactory 接口为不同的范围创建 GraphApiClient 请求。

请找到以下参考资料以了解更多详细信息:

在 ASP.NET Core 中使用 Microsoft Graph API | 软件工程 (damienbod.com)

使用承载身份验证保护 .NET Core API - Do.net Playbook

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM