【问题标题】:Authorization header is not setting未设置授权标头
【发布时间】:2021-11-21 03:23:19
【问题描述】:

我有一种登录方法,如下所示:

public async Task<ActionResult> Index(LoginModel loginModel)
{
    string url = "API_URL";

    var response = await client.PostAsJsonAsync(url, loginModel);

    if (response.IsSuccessStatusCode)
    {
        string result = await response.Content.ReadAsStringAsync();
        var jsonData = JObject.Parse(result);

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + jsonData["accessToken"]);

        return RedirectToAction("PostLogin");
    }
    else
    {
        ModelState.AddModelError("", "These credentials does not work. Hmm..");
    }

    return View(loginModel);
}

现在,如果用户成功登录,那么我将获得令牌,并且我将其设置在标题中。现在,我将用户重定向到 PostLogin 方法。

但在那种方法中,我无法访问该令牌。下面是代码。

public async Task<ActionResult> PostLogin()
{
    var accessToken = await HttpContext.GetTokenAsync("accessToken"); // Here I can't see token. and getting value as per below.

    return View();
}

即使我收到以下错误:

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action&lt;AuthenticationOptions&gt; configureOptions).

【问题讨论】:

  • client 变量在哪里定义?
  • @AleksaRistic 在控制器顶部: public class LoginController : Controller { HttpClient client = new HttpClient();
  • 看起来您还没有在 Startup 类中配置默认​​身份验证方案,例如 services.AddAuthentication(options =&gt; options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
  • @MartinCostello 我做了这样的改变: public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme); }
  • 仍然出现同样的错误

标签: c# asp.net asp.net-core asp.net-web-api


【解决方案1】:

您已评论说,在控制器开始时您有 HttpClient client = new HttpClient();,这是 HttpClient 的新实例

因此,在您的函数中,您使用以下行设置对象授权:client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + jsonData["accessToken"]);

之后,您将从当前的 HttpContext 获得用户授权,每次用户访问某个链接时都会发送该授权,并且您刚刚设置授权的 client 对象没有任何内容。

由于您正在重定向,因此您必须更改当前的HttpContext 授权标头,因为它将被带到重定向的请求中。通过更改HttpContext.Request.Headers["Authorization"] 来实现。问题是它只会持续该请求,因此您需要将令牌返回给客户端,以便他在每次发出请求时将其发送到标头中。

【讨论】:

  • 我明白你想说什么..但我很困惑我需要在我的登录方法或登录后方法中使用这个 HttpContext
猜你喜欢
  • 2015-11-05
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
相关资源
最近更新 更多