简体   繁体   中英

Blazor Client Side authentication jwt or cookies

So i am experimenting with client side blazor and trying to figure correct implementation for JWT or Cookie authentication. Suppose that i have a service that serves the tokens and refresh token on client side i will have multiple API Services that will need to use this token or cookies to create API requests.

So as i understand i will need to implement and API Service classes similarly as documented here https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

So in order to have a consistent authentication state an Authentication service should be introduced and injected to the API Service classes. This service will have the responsibility of doing auth,getting initial token and doing a refresh token when required.

So with the latest release of Blazor there is this new component called AuthenticationStateProvider, the use of it seem to be clear but the question is would it be correct approach to use this as a global Authentication service?

When using JWTs on unsecure clients like SPAs, it's a bad practice to implement refresh tokens, as those are meant to be private.

The current OIDC recommendation (for SPAs) is to implement the Authentication Code Grant strategy.

I would recommend you to take a look at Blazor-Auth0 library (author here), it implements the Authentication Code Grant strategy blacked on Auth0, so you don't need to reinvent the wheel (and it's free).

Even if you don't want to add a new dependency, you would find it as a good source of examples of how to implement JWT authentication and authorization in Blazor.

https://github.com/henalbrod/Blazor.Auth0

So HttpClientFactory is not supported on the client. In client-side Blazor, HttpClient is added to the DI system, and you can inject it into your components or classes.

So you want to use AuthenticationStateProvider as global Authentication service ? I'm not familiar with this component, but I'm afraid, from the short read I had after reading your question, that it is not an authentication system, but a tool to provide authentication state information, such as user age, etc. You still need to configure the Jwt middle ware, create a controller responsible for issuing the Jwt token, and so on. And I guess that you can employ the AuthenticationStateProvider to provide your client app with authentication state before a user, say, logged in and after, etc. I do hope I'm not wrong about it, at least not entirely.

So hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM