ASP.NET Core JWT Bearer Token Custom Validation

前端 未结 2 958
自闭症患者
自闭症患者 2020-12-08 03:10

After a lot of reading, i have found a way to implement a custom JWT bearer token validator as below.

Starup.cs Codes:

public void Conf         


        
相关标签:
2条回答
  • 2020-12-08 03:55

    For custom JWT validator, I created a JWTCosumerProvider class inhert to IOAuthBearerAuthenticationProvider. And implement the ValidateIdentity() method to check the identity Claim which i stored the client IP address at first place,then compare to current request Id address after.

    public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
    
            var requestIPAddress = context.Ticket.Identity.FindFirst(ClaimTypes.Dns)?.Value;
    
            if (requestIPAddress == null)
                context.SetError("Token Invalid", "The IP Address not right");
    
            string clientAddress = JWTHelper.GetClientIPAddress();
            if (!requestIPAddress.Equals(clientAddress))
                context.SetError("Token Invalid", "The IP Address not right");
    
    
            return Task.FromResult<object>(null);
        }
    

    JWTHelper.GetClientIPAddress()

    internal static string GetClientIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }
    
            return context.Request.ServerVariables["REMOTE_ADDR"];
        }
    

    hope this help!

    0 讨论(0)
  • 2020-12-08 04:12

    In ASP.NET Core HttpContext could be obtained using IHttpContextAccessor service. Use DI to pass IHttpContextAccessor instance into your handler and get value of IHttpContextAccessor.HttpContext property.

    IHttpContextAccessor service is not registered by defaul, so you first need to add the following in your Startup.ConfigureServices method:

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    

    then modify your CustomJwtSecurityTokenHandler class:

    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public CustomJwtSecurityTokenHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
        _tokenHandler = new JwtSecurityTokenHandler();
    }
    
    ... 
    
    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        var httpContext = _httpContextAccessor.HttpContext;
    }
    

    You should also use DI technique for JwtSecurityTokenHandler instantiation. Look into Dependency Injection documentation if you are new to all this stuff.


    Update: how to manually resolve dependencies (more info here)

    modify Configure method to use IServiceProvider serviceProvider:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
             ILoggerFactory loggerFactory, IApplicationLifetime appLifetime,
             IServiceProvider serviceProvider)
    {
        ...
        var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
        // and extend ConfigureAuth
        ConfigureAuth(app, httpContextAccessor);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题