代码之家  ›  专栏  ›  技术社区  ›  Franva

JWT身份验证如何在单独的API项目而不是AuthServer项目中验证http请求

  •  0
  • Franva  · 技术社区  · 5 年前

    特别是在读了几篇文章之后 this

    我制作了自己的ASP.NET核心解决方案

    1个项目(AuthServer) Authentication Authorisation ,和

    问题是: 如何在我的WebApi项目中验证http请求?

    我知道,一旦用户通过身份验证,客户端将持有令牌,对于随后的请求,它们都需要传递令牌,在服务器端,它会通过这段代码验证这些请求,这段代码位于AuthServer项目的Startup.cs中:

    services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x=> {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = context.Principal.Identity.Name;
                        var user = userService.GetById(userId);
                        if(user == null)
                        {
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
    
            });
    

    但是对于WebApi项目,我需要做什么来验证令牌? [授权]

    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    { ....}
    

    那么我应该做什么来验证我的WebApi项目中的令牌呢? 通过调用 AuthServer 每次请求传入时项目,然后在WebApi中执行代码?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Andriy Shevchenko    5 年前

    我假设您要运行两个单独的ASP.NET应用程序。 您可以验证以下请求 WebApi 通过向 AuthServer . 您可以创建一个自定义属性,它将完成此工作。 在WebApi项目中:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Primitives;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Security.Claims;
    using System.Threading.Tasks;
    
    namespace YourNamespace
    {
        public class YourCustomAttribute : TypeFilterAttribute
        { 
            public YourCustomAuthAttribute(
                : base(typeof(AuthFilter))
            {
                Arguments = new object[] {
                   // arguments gets passed to AuthFilter contructor,
    
                };
            }
        }
    
        public class AuthFilter : IAsyncAuthorizationFilter
        {
            private static readonly HttpClient http = new HttpClient();
    
            public AuthFilter()
            {
            }
    
            //Change it to fit your logic
            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                var authorizationHeader = context.HttpContext.Request.Headers["Authtorization"];
                if (authorizationHeader == StringValues.Empty)
                {
                    context.Result = new UnauthorizedResult();
                }
                else
                {
                    var response = await http.GetAsync(
                        "your AuthServer address/login/?token=" + authorizationHeader.ToString(),
                        HttpCompletionOption.ResponseHeadersRead //because we want only status code
                    );
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        context.Result = new ForbidResult();
                    }
                }
            }
        }
    }
    

    假设您在 LoginController 在AuthServer项目中

    [HttpGet]
    public IActionResult ValidateToken(string token)
    {
       //your logic here
    }
    

    [Authorize] .

    也可以查看这个链接(我用了一些代码) https://www.red-gate.com/simple-talk/dotnet/net-development/jwt-authentication-microservices-net/ 演示了如何手动验证Jwt令牌。

    Startup.cs :

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("AllowAllHeaders",
                          builder =>
                          {
                              builder.AllowAnyOrigin()
                                     .AllowAnyHeader()
                                     .AllowAnyMethod();
                          });
                });
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
            {
                app.UseCors("AllowAllHeaders");
            }
    
        2
  •  0
  •   Franva    5 年前

    经过数小时的阅读,我发现一篇文章在讨论是否将AuthServer与API服务器分离。