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.
Related
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.
I am implementing an OData endpoint on an ASP.NET application, and am working right now on the authentication part. I looked at the example at http://odata.github.io/WebApi/05-01-basic-auth/ for implementing HTTP Basic authentication. However, the example looks very weird to me, even though it the article gives an impression that this is how you implement generic custom authentication on a RESTful API.
e.g.:
It implements authentication on the stage of a pipeline where you are supposed to implement authorization. My understanding is that when OnAuthorization is called, you are supposed to already have the principal set and the only thing left to do is checking if the principal has enough access to perform the requested action.
What is the deal with that call to IsAuthorized? Isn't that supposed to be a side-effect free method?
So I basically would like to check from somebody who is more familiar with ASP.NET Web API to confirm if this is a) the correct way to do things b) a hackish but safe way to do things or c) something dangerous that should never be present in production code.
You are right, authentication should be implemented in separate AuthenticationFilter or even in HttpModule. You can find example here: authentication filter, http module.
I am trying to create secured MVC4 web API project. In this application knockout Js will access API service directly. I need authentication on his. I am confused how to apply authentication only on web api. I can’t use MVC authentication because other projects also share same API services.
Any one please suggest a good solution using knockout js and web api. I tried Thinktecture.IdentityModel but I am not able to use knockout Js in it.
this project is in .net 4.0.
Thanks in advance
thanks for the support
got solution
Use the [Authorize] attribute on the WebApi controllers
[Authorize(Roles="WebApiAccess")]
public class FooController : ApiController
{
}
You can send authN tokens before your Ajax request. Here is a similar SO question (with answer). You can add auth for your entire client app by creating a global 401 error handler (AngularJS, but the original question is generic jQuery).
I am trying to implement a custom authorization attribute on my Web API controllers, but came across an unexpected behavior.
<Authorize(Users:="myUser")>
Public Function GetTodoItems() As IQueryable(Of TodoItem)
The above code works very well: It will allow "myUser" to retrieve the items, bot nobody else is allowed access. However, when I try the same approach with my custom authorization, the entire check is skipped, and any user can access the resource. Neither the AuthorizeCore nor the OnAuthorization overridden methods in my derived class are called.
<MyAuth(Users:="myUser")>
Public Function GetTodoItems() As IQueryable(Of TodoItem)
The derived class inherits from System.Web.Mvc.AuthorizeAttribute, and the project is deployed on IIS, with Windows Authentication & Impersonation enabled, and Anonymous Authentication disabled.
If I add the same custom authorization to an MVC Controller, then it works. But on the API Controllers, nothing. If the Authorize attribute wouldn't have worked either, it would have made more sense. Am I missing something? Is this an expected behavior, or a bug in the Beta?
You should use System.Web.Http.AuthorizeAttribute from System.Web.Http.dll for Web API instead of System.Web.Mvc.AuthorizeAttribute.
That is, because namespace System.Web.Http.AuthorizeAttribute is derived from AuthorizationFilterAttribute. The filters are handled automatically by the Web API. In my own implementation I derived directly from AuthorizationFilterAttribute for handling of the basic HTTP authentication.
I've built my own custom implementation for Basic Authorization:
http://remy.supertext.ch/2012/04/basic-http-authorization-for-web-api-in-mvc-4-beta/
Maybe this helps.
I am using the WCF REST stater kit to build a plain xml over HTTP service. As part of this Im using a RequestInterceptor to do authentication. Inside of the RequestInterceptor I have access to a System.ServiceModel.Channels.RequestContext object from which i can get the request url, querystring params and other helpful things. What I cannot work out is how to get access to the HttpContext of the request. I have several things stored in the HttpContext which I want to access inside the requestInterceptor but Im struggling to get to them. When I use the quickwatch inside Visual Studio I can see that it is there buried inside private members of the requestContext. Can somebody show me how to access the HttpContext, perhaps using reflection on the RequestContext object?
You can access ASP.NET's HttpContext inside any WCF service hosted in ASP.NET as long as you turn on compatibility. This is done in two steps:
Apply the AspNetCompatibilityRequirementsAttribute to your service class and set the RequirementsMode property to Required
Make sure you enable compatibility by configuring the following:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />
</system.serviceModel>
Once you've done that, you can access the current HttpContext instance at any time using the static Current property. For example:
foreach(HttpCookie cookie in HttpContext.Current.Request.Cookies)
{
/* ... */
}
Note that enabling integration with the ASP.NET runtime does incur some additional overhead for each request, so if you don't need it you can save some performance by not enabling it and just using the System.ServiceModel.Web runtime instead. You have access to pretty much all the information you need using the HttpRequestResponseMessageProperty and HttpResponseMessageProperty classes.
For more information on the subject, see this section of MSDN titled WCF and ASP.NET.