承载令牌WEB API asp.net核心,无需重定向 [英] Bearer token WEB API asp.net core without redirection

查看:82
本文介绍了承载令牌WEB API asp.net核心,无需重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是asp.net核心的新手.我正在尝试使用jwt身份验证和来自Google,Facebook等的OpenOauth来制作小型Web服务.

I'm new to asp.net core. I'm trying to make a small web service using jwt authentication and OpenOauth from Google , Facebook, ...

我已经阅读了这篇文章: https://stormpath.com/blog/token-authentication-asp-net-core

I've read this post : https://stormpath.com/blog/token-authentication-asp-net-core

这篇文章是关于在ASP.Net核心中使用jwt进行身份验证的,但是,我还想验证用户是否在系统中被禁用或处于活动状态.

This post is about authenticating with jwt in ASP.Net core, but, I also want to verify whether the user is disabled or active in my system.

我的数据库有一个包含4列的表:Id,名称,密码,状态(0-禁用| 1-有效).

My db has one table with 4 columns: Id, Name, Password, Status (0 - Disabled | 1 - Active).

我如何归档我的目标?

有人可以帮我吗?

P/S:我已经在google中搜索了asp.net中有关jwt的完整教程,但是内容很少.赞赏用于身份验证流程的完整源代码.

P/S : I've searched google for complete tutorials about jwt in asp.net but there were so little. Full source code for authentication flow is appreciated.

推荐答案

我测试了三种方法(它们有效,但我不知道哪种方法正确).

There are three way i tested(they worked, but i don't know which one is correct way).

首先使用OnTokenValidated事件:

 OnTokenValidated = async (ctx) =>
 {
       if(user is disabled)
       {
           ctx.Response.Headers.Append(
                        HeaderNames.WWWAuthenticate,
                        ctx.Options.Challenge);
           ctx.SkipToNextMiddleware();
       }
 }

第二个在jwt中间件之后使用Use方法:

Second is using Use method after jwt middleware:

        app.Use(async (context, next) =>
        {
            var auth = await context.Authentication.AuthenticateAsync("Bearer");
            if (auth.Identity.IsAuthenticated && user is disabled)
            {
                context.Response.Headers.Append(
                      HeaderNames.WWWAuthenticate,
                      "Bearer");
            }
            await next();
        });

最后一次使用SecurityTokenValidators:

public class CustomSecurityTokenValidator  : JwtSecurityTokenHandler
{
    public CustomSecurityTokenValidator()
    {
    }

    public override ClaimsPrincipal ValidateToken(string securityToken,
        TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        var principal = base.ValidateToken(securityToken, validationParameters, out validatedToken);
        if(user is disabled)
        {
            throw new SecurityTokenNotYetValidException();
        }
        else
        {
            return principal;
        }
    }
}

..... in Startup.cs ...........
var options = new JwtBearerOptions()
{
     //....
}
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new CustomTokenValidator());
app.UseJwtBearerAuthentication(options);

这篇关于承载令牌WEB API asp.net核心,无需重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆