承载令牌WEB API asp.net核心,无需重定向

编程入门 行业动态 更新时间:2024-10-25 16:18:53
本文介绍了承载令牌WEB API asp核心,无需重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

I've read this post : stormpath/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中有关jwt的完整教程,但是内容很少.赞赏用于身份验证流程的完整源代码.

P/S : I've searched google for complete tutorials about jwt in asp 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核心,无需重定向

本文发布于:2023-10-29 07:48:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   重定向   核心   WEB   asp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!