将授权代码转换为ASP.NET Core MVC中的access_token以调用.NET Framework API [英] Convert authorization code to access_token in ASP.NET Core MVC to call a .NET framework API

查看:336
本文介绍了将授权代码转换为ASP.NET Core MVC中的access_token以调用.NET Framework API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用.NET Framework API的ASP.NET Core MVC应用程序.

I have an ASP.NET Core MVC application which calls a .NET framework API.

MVC应用程序使用混合流,并使用Startup.cs中的以下代码获取id_token和授权代码:

The MVC application uses the hybrid flow and gets the id_token and authorization code using the following code in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.Authority = Configuration["AzureAD:Instance"] + 
             "/" + Configuration["AzureAD:TenantId"];
            options.ClientId = Configuration["AzureAD:ClientId"];
            options.Secret = Configuration["AzureAD:Secret"];
            options.Callback = Configuration["AzureAD:Callback"];
            options.ResponseType = "code id_token";
            options.SaveTokens = true;
        });

    services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "sign-in",
            template: "signin-oidc")};


        ...

});

在控制器中,当我检查HttpContext时,可以获得id_token和授权代码.但是我需要将access_token传递给API.

In the controller, when I check the HttpContext, I can get the id_token and authorization code. But I need to pass the access_token to the API.

如何从授权码中获取access_token?

MSAL/ADAL是否用于上述目的?如果可以,如何使用MSAL获取access_token?

Is MSAL/ADAL used for the above purpose? If so how can I get the access_token using MSAL?

有人可以给我指出一些示例代码吗?

Could someone please point me to some example code?

推荐答案

您是正确的,ADAL/MSAL用于获取令牌以调用安全的Web API.如果使用OpenID Connect中间件,则在OnAuthorizationCodeReceived事件中,可以使用ADAL/MSAL获取带有授权代码的访问令牌.

You are correct , ADAL/MSAL are used to acquire tokens in order to call secured Web APIs. If using OpenID connect middleware , in OnAuthorizationCodeReceived event , you can use ADAL/MSAL to acquire access token with authorization code .

如果使用Azure AD v1.0,则可以引用此处是另一篇带有代码示例的文章.

If using Azure AD v1.0 , you could refer to this code sample which use ADAL to acquire access token . Check the OnAuthorizationCodeReceived event. Here is another article with code sample .

如果使用Azure AD v2.0(用于使用Work和School帐户以及Microsoft Personal帐户登录用户),则可以参考下面的链接,了解使用MSAL的代码示例:

If using Azure AD v2.0 (to sign-in users with Work and School accounts and Microsoft Personal accounts) , you can refer to below link for code samples which use MSAL :

https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2

您的方案与第四个代码示例相匹配:4-WebApp-your-API.

Your scenario matches the forth code sample : 4-WebApp-your-API .

该代码示例使用Microsoft.Identity.Web库,这使开发人员可以更轻松地在Microsoft身份平台上为开发人员构建Web Apps,并将您的api添加为作用域:

That codes sample use Microsoft.Identity.Web library which make it easier to build your Web Apps on top of Microsoft identity platform for developers , add your api as scope :

services.AddAzureAdV2Authentication(Configuration)
        .AddMsal(new string[] { Configuration["TodoList:TodoListScope"] })

并获得令牌:

var accessToken = await this._tokenAcquisition.GetAccessTokenOnBehalfOfUser(this._contextAccessor.HttpContext, new[] { this._TodoListScope });

这篇关于将授权代码转换为ASP.NET Core MVC中的access_token以调用.NET Framework API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆