在 ASP.net Core Razor 页面 WebApp 中读取令牌

问题描述 投票:0回答:1

我有一个托管在 Azure 中的 ASP.NET Core razor Pages Web 应用程序,使用应用程序注册和 AD,到目前为止我可以成功登录、验证并生成不记名令牌。我正在尝试调用 Azure APIM 中具有策略的 API。

我可以手动检查登录并复制令牌值并使用邮递员调用 API。但是,我无法使用该令牌作为 web 应用程序中的变量来为 POST 请求设置授权标头。如果我向应该调用令牌的操作添加断点,我只会得到值:null。

到目前为止,我已经尝试了我能找到的所有文档和信息,但总是指向:

using System.Net.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;

public class IndexModel : PageModel
{
    private readonly ITokenAcquisition _tokenAcquisition;
    private readonly string _apiUrl;

    public IndexModel(ITokenAcquisition tokenAcquisition, IConfiguration configuration)
    {
        _tokenAcquisition = tokenAcquisition;
        _apiUrl = configuration["ApiUrl"]; // Replace with the URL of your API endpoint.
    }

    public async Task OnGetAsync()
    {
        string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { "your_api_scope" });

        using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            try
            {
                HttpResponseMessage response = await httpClient.GetAsync(_apiUrl);

                if (response.IsSuccessStatusCode)
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    // Process the API response as needed.
                }
                else
                {
                    // Handle the unsuccessful response here.
                }
            }
            catch (HttpRequestException ex)
            {
                // Handle exceptions here.
            }
        }
    }
}

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task<IActionResult> Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
 string json = await client.GetStringAsync(url);
}

尽管我可以看到登录时已成功创建令牌,但两者都在令牌上返回空值

asp.net-core azure-web-app-service razor-pages azure-api-management bearer-token
1个回答
0
投票

假设您已登录并通过身份验证,您是否尝试过以下操作:

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    private IConfiguration _configuration { get; }

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;            
    }

    public async void OnGet()
    {
        if (User.Identity.IsAuthenticated)
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");
        }

    }
}

现在您可以构造一个 HttpClient 并将其设置为不记名令牌,例如:

var apiClient = new HttpClient();
        apiClient.SetBearerToken(accessToken);
© www.soinside.com 2019 - 2024. All rights reserved.