【问题标题】:How am I supposed to configure Jwt Bearer authentication?我应该如何配置 Jwt Bearer 身份验证?
【发布时间】:2017-08-14 21:59:26
【问题描述】:

我正在尝试制作一个使用 Jwt 令牌身份验证的 Web 应用程序,登录等工作正常。 现在我正在尝试添加对谁可以访问哪些页面等的授权。在我的控制器上,我添加了[Authorize]。但是当我登录并尝试执行其中一项操作时,我总是得到一个空白页面,当我检查它时,该操作总是返回 401 Unauthorized,有什么建议吗?

用于将授权标头发送到 Api 的我的标头服务:

using System.Collections.Generic;

namespace RelationizeWeb.Facade.Services
{
    public class HeaderService : IHeaderService
    {
        private const string AuthorizationHeaderKey = "Authorization";
        private const string BearerHeaderValue = "Bearer";

        public Dictionary<string, List<string>> CreateAuthorizationHeader(string token)
        {
            var dict = new Dictionary<string, List<string>>
            {
                { AuthorizationHeaderKey, new List<string>{ $"{BearerHeaderValue} {token}" } }
            };
            return dict;
        }

        public Dictionary<string, List<string>> CreateHeader(string key, string value)
        {
            var dict = new Dictionary<string, List<string>>
            {
                { key, new List<string> { value } }
            };
            return dict;
        }
    }
}

我们在 OpinionMakerService 中提出的 Api 请求示例:

public IEnumerable<OpinionMaker> GetOpinionMakers(JwtTokenResponse jwt)
    {
        try
        {
            return (List<OpinionMaker>)_relationizeApiAgent.GetOpinionMakersWithHttpMessages(_headerService.CreateAuthorizationHeader(jwt.AccessToken)).Body;
        }
        catch(Exception)
        {
            return null;
        }
    }

【问题讨论】:

  • 你在使用 .NET Core 吗?
  • 是的,我正在使用 .NET Core 框架
  • 当我们几周前开始这个项目时,我们总是总是重定向到登录页面,现在我们添加的不仅仅是一个登录页面,这还不够。我们还想要一些公共页面,并认为这是最好的方法
  • 在没有 IIS 的情况下运行它我设法捕获了这个错误Authorization failed for user: (null). 有什么建议吗?
  • 未为登录用户设置声明身份

标签: c# model-view-controller jwt


【解决方案1】:

您可以使用 azure 为您的应用程序生成 JWT。您需要在 REST api 的 StartUp.cs 文件中调用名为 UseJwtBearerAuthentication 的扩展方法,并对控制器使用 [Authorize] 属性。 UseJwtBearerAuthentication 方法的工作原理如下

app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                Authority = <your auth name>,
                Audience = <target audience URL>
            });

请参阅下面的链接以获取更多参考 1.https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/

  1. https://pioneercode.com/post/authentication-in-an-asp-dot-net-core-api-part-3-json-web-token

您可以使用像 ADAL.JS 这样的客户端库来调用 azure 服务以获取 JWT 不记名令牌,然后将每个请求中的令牌发送给控制器。它将在每个请求中进行验证。我们在带有 Azure JWT 身份验证的 Angular2 应用程序中采用了这种方法。

adal.js 的链接 https://github.com/AzureAD/azure-activedirectory-library-for-js

资源: https://blogs.msdn.microsoft.com/premier_developer/2017/04/26/using-adal-with-angular2/

编辑:在从另一个控制器调用控制器之前,您可以使用以下代码访问 JWT 令牌并将其添加到 Authorization 标头中

 HttpClient client = new HttpClient();
    var token = <add your token here>; // call GetToken() method here and extract access_token from JwtTokenResponse class property.
    client.DefaultRequestHeaders.Authorization = new 
    AuthenticationHeaderValue("Bearer", token.Substring("Bearer ".Length).Trim());

    //call the api method using SendAsync() or PostAsyc() etc.

【讨论】:

  • 您能解释一下这些选项的作用吗?以及我如何找出在权威和观众中放入什么?因为我对此很陌生......
  • 检查 MSDN 链接.. 那里解释了每个选项。
  • 即使像这样配置它,我仍然只收到 401 响应,即使我很确定我已登录。
  • 您在使用 azure 和 adal.js 吗?您必须在调用控制器中的操作之前从客户端发送令牌以验证服务器端。检查 chrome 中的网络选项卡,看看您是否正在发送不记名令牌。
  • 不,我不是,令牌已经从控制器发送到控制器,只是无法验证它是否有效。另外我无法将角度转换为 C#...
猜你喜欢
  • 2020-07-23
  • 2021-07-03
  • 1970-01-01
  • 2018-08-29
  • 2018-07-10
  • 2021-04-15
  • 2016-01-02
  • 1970-01-01
  • 2020-02-01
相关资源
最近更新 更多