本文介绍了Jwt身份验证在Blazor Serverside中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在具有角色和所有功能的Blazor Client Hosted项目中使用了Jwt身份验证,但是当我在Blazor Server端执行相同的操作时,它不起作用,例如,在Header中设置令牌后:

I used Jwt authentication in a Blazor Client Hosted project with roles and everything (using Identity), But when I do the same thing in Blazor Server side It doesn't work, For example After I set the token in the Header:

client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Model.Token}");
            Console.WriteLine($"Is authenticated = {httpContext.HttpContext.User.Identity.IsAuthenticated}");

IsAuthenticated返回false,当我导航到主页(以引起刷新)时,IsAuthenticated仍然返回false,并且无法通过HttpContext.User.Identity.Name访问任何用户名!是否有解决方法? (Blazor服务器端预览6中的默认身份验证仅限于本地化和其他用途,我不想使用它)

IsAuthenticated returns false, and when I navigate to home page (to cause a refresh) the IsAuthenticated still returns false and No user name is accessible through HttpContext.User.Identity.Name!! Is there a workaround for this. (the default authentication in Blazor serverside preview 6 is limited for Localization and other things and I don't want to use it)

推荐答案

我可以解决没有Cookie或标头的问题,我创建了一个Auth类,其中包含用户名,经过身份验证,角色和方法IsInRole,然后注入(作为单例) ),该类适用于使用或填充该类的每个视图,然后在成功登录时填充它(我使用Identity checkpasswordsigninasync).我填充该类并通过应用程序使用它,在注销时,我只是创建一个空实例.我认为,因为所有在服务器上运行的类都是安全的,并且它的唯一局限性在于页面刷新身份验证丢失并且HttpContext.User为空.

I could solve my problem without a cookie or header, I created an Auth Class with username, isauthenticated and roles and method IsInRole in it and then injected (as singleton) this class to every view that use or populate this class and then populate it on success login (I used Identity checkpasswordsigninasync) I populate this class and use it through application, On Logout I simply create an empty Instance.I think because everything runs on the server this class is safe and its only limitation is that on page refresh authentication is lost and HttpContext.User is empty.

编辑:

首先,在刷新时,单例服务不会丢失其数据,因此身份验证模型不会为空.

firstly, on Refresh the singleton services does not loose their data so Authentication Model does not empty.

第二:如果您认为此Auth模型使编程不熟悉,则可以在登录时使用IEnumerable< Claim>设置ClaimPrincipal. -声明变量-像这样:

Second: If you feel this Auth Model Makes programming unfamiliar, I could set ClaimPrincipal on login using an IEnumerable<Claim> -claims variable- like this:

httpContext.HttpContext.User = new System.Security.Claims.ClaimsPrincipal(new ClaimsIdentity(claims));

然后像在Web窗体中一样使用直观的HttpContext.User.IsInRole和HttpContext.User.Identity.Name.

then use Intuitive HttpContext.User.IsInRole and HttpContext.User.Identity.Name like we did in Web Forms.

这篇关于Jwt身份验证在Blazor Serverside中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:55