Bearer token WEB API asp.net core without redirection

≡放荡痞女 提交于 2020-01-05 05:39:09

问题


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

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

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.

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

How can I archieve my goal ?

Can anyone help me please?

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.


回答1:


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

First is using OnTokenValidated event :

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

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();
        });

Last is using 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);


来源:https://stackoverflow.com/questions/39762599/bearer-token-web-api-asp-net-core-without-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!