Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 3949

How to use custom JWT Authentication in .NET 8 Blazor App with Auto Render Mode

$
0
0

when I create a Blazor application it generates server and client application. I am creating Api's in the server side of the application. So when app is render it is render in server mode and my pages are rendered form the clinet. i have created a custom AuthenticationStateProvider and register it on both server and client side.The Problem is I need to store the token somewhere, which should be accessible form the server and client.

public class CustomAuthenticationStateProvider : AuthenticationStateProvider{    private readonly IHttpContextAccessor _httpContextAccessor;    private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());    public CustomAuthenticationStateProvider(IHttpContextAccessor httpContextAccessor)    {        _httpContextAccessor = httpContextAccessor;    }    public override async Task<AuthenticationState> GetAuthenticationStateAsync()    {        var token = _httpContextAccessor.HttpContext.Request.Cookies["token"];        if (string.IsNullOrEmpty(token))            return new AuthenticationState(_anonymous);        var tokenHandler = new JwtSecurityTokenHandler();        var identity = new ClaimsIdentity(tokenHandler.ReadJwtToken(token).Claims, "jwt");        var user = new ClaimsPrincipal(identity);        return await Task.FromResult(new AuthenticationState(user));    }    public void UpdateAuthenticationState(string token)    {        if (string.IsNullOrEmpty(token))        {            _httpContextAccessor.HttpContext.Response.Cookies.Delete("token");            NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_anonymous)));            return;        }        var tokenHandler = new JwtSecurityTokenHandler();        var identity = new ClaimsIdentity(tokenHandler.ReadJwtToken(token).Claims, "jwt");        var user = new ClaimsPrincipal(identity);        var cookieOptions = new CookieOptions        {            Expires = DateTime.Now.AddHours(1),            HttpOnly = true,            SameSite = SameSiteMode.Strict,            Secure = true        };        _httpContextAccessor.HttpContext.Response.Cookies.Append("token", token, cookieOptions);        NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));    }}

When using httpContextAccessor client don't have this object.Error blazor.web.js:1 Error: One or more errors occurred. (Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Client.CustomAuthenticationStateProvider'.)

when using Local storage or session storage Server gives error with JSRuntime interpole


Viewing all articles
Browse latest Browse all 3949

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>