在两个ASP核心API之间共享Jwt令牌

时间:2019-10-02 14:15:09

标签: c# asp.net-core jwt token

我在这里遇到麻烦。 我正在尝试构建第二个asp核心api,它将共享创建的jwt令牌购买我的主要aspcore api aka:授权服务器。 但是我无法使它正常工作。

这个想法是我的有角度的客户端将从我的主api(授权服务器)获取一个令牌,并发送相同的令牌以从其他api获取数据,这将不得不与auth服务器进行检查,我猜该令牌是否有效

我认为这是在配置otpion中的某个地方:

            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
                           // Ensure the token audience matches our audience value (default true):
                    ValidateAudience = true,

                };

我在我的配置文件中:

  "Jwt": {
    "Key": "METAPRODUCTIQUE2904",
    "Audience": "http://localhost:52771/",
    "Issuer": "http://localhost:52771",
  },

然后,主应用程序在端口52771上运行以进行测试,而我当前的辅助应用程序在端口52772上运行 但我认为我做错了什么,但无法弄清楚 我非常感谢你们的一些想法

1 个答案:

答案 0 :(得分:1)

首先,让我们了解它的工作原理。

1) user ---------------------(Get Token) ---------------------> AuthServer
2) AuthServer -----------------(Token)------------------------> user
3) user ----------(Request with Token as auth header)---------> OtherServers

在步骤2中,AuthServer检查用户权限并创建一个包含用户信息,权限和其他内容的数据包,然后使用您提供给base64字符串的key对其进行加密。我们称之为Token

我们在其他服务器中也有key。当收到请求时,他们首先尝试使用key对其进行解密。如果一切正常,那么另一个服务器现在就拥有了用户信息和权限以及其他内容。

因此AuthServer不需要连接到其他服务器,它们可以相互配合。

在两个服务的startup类中,您应该具有以下代码:

 public void ConfigureServices(IServiceCollection services)
        {
            ...
            // JWT
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                        .GetBytes("MySpecialKey")),
                    ValidIssuer = "MainServer",
                    ValidAudience = "Sample",
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            ...
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ...
            app.UseAuthentication();
            ...
        }

authorization server的一项服务中,您应该实现一种方法来为注册用户生成令牌:

public async Task<string> GenToken()
        {
            // check if the user has the required permissions
            ....

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, "Username"),
                }),
                Expires = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes("MySpecialKey")), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }

现在,您可以在控制器或API的顶部使用[Authorize]属性。

[Authorize]控制器或API的每个请求都应包含带有密钥Authorization和值bearer USERTOKEN的标头