how to jwt authentication blazor server without microsoft identity? - authentication

i'm using blazor server ( not use webapi, httpclient and ...)
and i want to use jwt for authentication
Where should I store token? localStorage or cookie?
how to send jwt to server all of the request?
I had to use AuthenticationStateProvider?
I used httpContext but I got an error unless it fit into the cshtml
file I also used localstorage inside AuthenticationStateProvider but
just got an error
also , which one is better? blazor server (one project) or
blazor server with webapi?(two project, blazor server and api)

which one is better? blazor server (one project) or blazor server with webapi?(two project, blazor server and api)
There is no such thing better. It all depends on your requirements. Do you need or do you wish to use a Wep Api ? If you're not going to use a Web Api, don't use a Jwt authentication. A Jwt access token is used when you want to access A Web Api endpoints. You can use the Identity UI system instead, to authenticate your users. Which you're probably familiar with, and can be set up and run in a little while.
Where should I store token? localStorage or cookie?
You may use the JavaScript local storage to store and retrieve Jwt tokens.
how to send jwt to server all of the request
You mean to a server Wep Api endpoint, right ?
Retrieve the Jwt token from your local storage ( provided that your app has
already authenticated the user, and stored the token in the local storage)
as for instance:
#code {
List<Hotel> hotels;
protected override async Task OnInitializedAsync()
{
// Read the token from the store
var token = await TokenProvider.GetTokenAsync();
var httpClient = clientFactory.CreateClient();
httpClient.BaseAddress = new Uri("https://localhost:44381/");
// Perform HTTP call to your Web Api end point Hotels
// Deserialized the response into a list of hotel objects.
hotels = await httpClient.GetJsonAsync<List<Hotel>>("api/hotels",
new AuthenticationHeaderValue("Bearer", token));
}
}
Note how I pass the Jwt token to the Wep Api endpoint.
I had to use AuthenticationStateProvider?
Do you ask whether to use the AuthenticationStateProvider ?
Ordinarily, you don't use the AuthenticationStateProvider. Its subclass, ServerAuthenticationStateProvider, is automatically added to the DI container, so you can inject it to your components and use it. In Client side Blazor you'll have to create a custom AuthenticationStateProvider.
However, you'll have to use components such as AuthorizeRouteView and AuthorizeView, which need the AuthenticationState object to function, and it is provided by the AuthenticationStateProvider.
See here, in my answer, how I use them...
Update:
I mean, which is better? blazor server with signalr or blazor with webapi?
Blazor Server App is SignalR-based SPA, meaning that the communication between the client-side of the application (browser) and the server-side of the application (server) is implemented by SignalR. Generally speaking, SignalR, in the current context, is a means of transportation and communication between the two parts which constitutes A Blazor Server App, mentioned above.
A web Api, however, in the current context, is an API over the web which can be accessed using HTTP calls. More specifically, it is an application you add to your project with controllers that expose end points you can call using HttpClient service.
As you can see, it's not SignalR versus Web Api, as this terms refer to two completely different concepts. You may ask about the difference between SignalR versus HTTP protocols...
I'll ask the correct question instead of your question: How should I access data with my server-side Blazor app and what should I use services or Web Api ? I've answered this question at length in my other answers. You can also consult the docs.
Note that you should create a Web Api project of you wish to use it from your Blazor Server App.
and how authorize blazor with signalr?
I guess that by now you know the answer. Server Blazor App is SignalR-based. You don't do anything in that regard. Just create such type of project, and start coding, learning Blazor component model, which is the heart of Blazor.
Wrapping up, I just want to mention that Blazor client-side or Blazor WebAssembly Apps, do not employ SignalR, but rather WebAssembly, in case your confusion comes from here.

Related

Identity Server scaffolding and Blazor WebAssembly

I have a hosted Blazor WebAssembly App and I tried to scaffold identity server in the project App.Server. It's working but now I have a mix of cshtml view files in the App.Server (which was intended to be only a asp net core web api). I found hard to integrate the Blazor UI and cshtml files to have a nice user experience.
I was expecting to have a separate pure web api with identityserver api and Blazor taking care of the pages/views and api calls. Is it possible to move those cshtml to Blazor and manage the pages from there or the scaffolding has been done that way because is not?
No, you can't move those Razor Pages pages to your front-end Blazor. But you can design them in such a way as to create the impression that, when the user, for instance, is redirected to the Login page, the Login Razor Pages page is part of the Blazor front-end. I've seen an example of that, and must admit that I couldn't discern it without seeing the source code.
Having a dedicated Web Api project or having Web Api end points in your Blazor server project has nothing to do with the Identity UI not being part of the Blazor front-end.
I was expecting to have a separate pure web api with identityserver api and Blazor taking care of the pages/views and api calls.
You can create a Blazor WebAssembly stand alone project, add a Web Api project, and an IdentityServer4 project, in which case, the flow of OpenID Connect is such that your users wanting to log in are redirected to the Login page provided by the default template of the project, but you can still design the pages to look as though they are part of the Blazor front-end.
The only viable solution that can satisfy your whims is to use Bearer Authentication; that is your Web Api produces Jwt token for users, which are passed to your front-end, and stored in the local or session storage. In that case, your Login page can be a Razor component that gather credentials from the user, and pass them to the Web Api appropriate end points via the Fecth API (this is the HttpClient service in Blazor)... This was the method we adopted before the Blazor team have created the current authentication system of Blazor. Personally I wouldn't recommend one to do that unless he is proficient in Blazor and other fields, and he's ready to invest a great deal of time for developing it. I guess your solution should be deception: let the user think that he's never left the space of the Blazor SPA...

Blazor WASM (Client Side Only) - How to make HTTP Request to different APIs?

So I'm coming from Xamarin world trying to build a Blazor App. And I'm struggling with a high level understanding of why Blazor Apps ( client side only ) cannot make a basic HTTP get call to say google.com or any other http get/post call to different resources/urls?
Can someone break it down for me, am i crazy? how would i ever implement maps.google.com or other http request I'm going to need to make.
I do notice anything with a package, like SendGrid or B2C or Cosmos Nuget Packages seem to work fine... how do they get around the different domain names ?
Can i simply say on my webserver : (in English) - allow requests to google.com and someoneElsesApi.com
or would i have to contact google and have them allow my Blazor app to make calls?
Just really struggling with how to use Blazor Client Only PWA app if it cant connect or call to anything else on the web... seems pointless if a Blazor app cannot make any http calls to other services.
Ok, so yes... I found an Public Open API to test a request against, and it does work from a Blazor WASM (Client only). More specifically the below works just fine..
#inject HttpClient HttpClient
...
string responsString = await HttpClient.GetStringAsync("https://rickandmortyapi.com/api/character/5");
The problem i was having which seems confusing:
Both
Blazor WASM
Xamarin Forms apps
can both call an open public Web API just fine from HTTP Client.
But...
When I create an ASP.NET core API and publish it allowing anonymous access in azure,
Xamarin Forms can call that API
Blazor WASM cannot call it unless i specify CORS correctly in the Web API
So with my inexperience with Blazor WASM i assumed it could not do this.. while Xamarin can. So this changes to ... how is it that the Web API i created in Azure + ASP.net Core Web API - just allows the Xamarin App to call it (without CORS specification)... while CORS Must be set correctly for a Blazor WASM?

Blazor WebAssembly - how to securely consume private/restricted API?

I want to build 2 apps.
Private API in .NET that takes care of database access / processing of data.
Blazor WebAssembly app which will connect to this API securely, to search data.
Since Blazor WebAssembly DLLs can be decompiled, I can't use any private/secret keys in the APP.
I don't want anyone being able to use the API if they discover the endpoints. Only the Blazor APP can use the API (and any other app I might build in the future).
How should I approach this? Is it even possible to do it securely or should I go Server Side?
Secure ASP.NET Core Blazor WebAssembly explains how to secure a Blazor WASM app
Blazor WebAssembly 3.2.0 Preview 2 release now available explains how to use IAccessTokenProvider to get the access token to authentify your applicaton on API.

How to access HttpContext from Blazor

Hello i have an application on which i am doing a custom authentication on the server side.
Now i need to port this logic to a Blazor Client.I do not know how i can access HttpContext data such as:
HttpContext.Request.Host.Value
HttpContext.User.Identity.IsAuthenticated
and also how to use the extension method Microsoft.AspNetCore.Authentication.SignInAsync extension method.
How can i get the HttpContext from the client ?
Sending the HttpContext object to the client-side Blazor is a bad idea. HttpContext Accessor is used to inject the HttpContext into classes that have no direct access to the HttpContext object. If you still want to do it, see comment by # Flores.
I'm not sure what custom authentication system you want to create, but I'd suggest you learn first how to do that the Blazor way. See comment by #dani herrera for a sample by the Blazor team. This sample will also give you the idea of what data you should pass to the client-side Blazor. Of course you can extend this authentication system in many ways: Jwt authentication can be a good exercise for you in extending the Blazor Auth System.

ASP.Net MVC and WebApi authentication using Identity server

I am new to Identity server and wants to secure my two apps (MVC, Webapi) using it.
I have seen the example where we can invoke the webapi from MVC action method and SetBearerToken that was issued to the the MVC application. I am referring the below sample:
https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html
This is typical example of server to server communication where we are using access token issued to the MVC app for Web api.
In the same scenario, I want to call webapi from Javascript client(fro ex Angular or any one) using same access token.
"I want to pass the the access token issued to the MVC application to call WebAPI from JavaScript"
How can I utilize the token that was issued to my MVC application from the JavaScript client?
Thanks
They should be treated as different client in my opinion, I guess they are different site? For your Javascript client you should be able to find example here , you can use the javascript lib that provided in the example or write one yourself
Once you get the token, then you can call your API using AJAX, where you might face CORS problem if your webapi is on a different domain, well...that is different topic.
Hope that helps