Jwt Authentication doesn't work in Blazor Serverside

試著忘記壹切 提交于 2019-12-24 18:22:32

问题


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 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)


回答1:


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.

EDIT:

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

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

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



来源:https://stackoverflow.com/questions/57125763/jwt-authentication-doesnt-work-in-blazor-serverside

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