Make Strawberry Shake request from Blazor with or without credentials - asp.net-core

In my Blazor app (which uses Azure B2C), I want to be able to call an endpoint whether the user is authenticated or not.
I've searched quite a bit, and everything I find says I should create two HttpClients (example), one for anonymous and one for authenticated, or use IHttpClientFactory with named clients.
The problem is I am using Strawberry Shake which only allows me to configure HttpClient once (it is using a named client and IHttpClientFactory internally).
Their documentation gives a simple example of setting authentication:
services
.AddConferenceClient()
.ConfigureHttpClient((serviceProvider, client) =>
{
var token = serviceProvider.GetRequiredService<ISomeService>().Token;
});
I thought I could use this to conditionally select which handler(s) I wanted, but the only ways I can find to get the token (IAccessTokenProvider.RequestAccessToken()) or validate authentication (Task<AuthenticationState>) require async calls, which are not allowed in this context. Even .Result doesn't work (not that I wanted to use it anyway).
My last thought is that maybe I could accomplish this by inheriting from BaseAddressAuthorizationMessageHandler or chaining handlers, but I can't figure out how. I even tried copying the source code and modifying it, but still couldn't get it to work (UPDATE: Actually, that did work, but it still seems less than ideal).
So many approaches seem workable, but ultimately fail me. How can I get this to work? Please provide code example if possible.

Related

Running method on every call using express-graphql

I'm using express-graqphl and was wondering if there is any concept of running a function before each graphql endpoint is executed? I'd like to have this for things like validating JWTs and other things. I realize we could use express for this, e.g.
app.use('/graphql`, doChecks);
but I'd like for the graphql handler to throw an error so it'll be inside the errors: [] list in the results giving the client a consistent experience with the api. Is there any direct support for this in the package?
The context function is executed before every request. If you're using Apollo v4+ then here are the docs
The context function is most often used to manage auth, including reading and validation of security tokens.

Serilog using EnrichDiagnosticContext with additional properties not being logged in SignalR Hub

I have recently implemented Serilog logging into my ASP.NET Core/.NET5 web app that uses SignalR. I'm using the Elasticsearch sink and everything is largely working as expected. I decided to add some additional HttpContext properties to be logged on each request, so I went down the road of extending the call to UseSerilogRequestLogging() in StartUp.cs as to enrich the diagnostic context with a couple of extra properties (mainly because this seemed like the simplest way to do it):
app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("HttpRequestClientIP", httpContext.Connection.RemoteIpAddress);
diagnosticContext.Set("UserName", httpContext.User?.Identity?.Name == null ? "(anonymous)" : httpContext.User.Identity.Name);
};
});
At first, this seemed to work as expected until I noticed it wasn't always working. I really want the extra properties logged on all log records written, and it seems to work fine on log records that are written automatically by Serilog when typical HTTP GETs, HTTP POSTs, etc. occur... But in my Signalr Hub class, I have a couple of places where I'm manually writing my own log records like Logger.Log(LogLevel.Information, "whatever.."), but these extra properties are simply not there on these records.
What am I missing here? Is it something about this being in a Signalr Hub that makes them unavailable? Or perhaps there's something I'm doing wrong with my Logger.Log() calls?
Any ideas would be appreciated.
Thanks-
It's not gonna to work with signalR.
Behind the screen, app.UseSerilogRequestLogging make use of a middleware in the request pipeline, that call RequestLoggingMiddleware as what you can see in detail here.
SignalR use the first Http request to setting to connection up to websocket, which won't goes through the pipeline at all. Therefore, doesn't have anything to do with RequestLoggingMiddleware, which you are using to logging out the request.
I finally ended up going with a couple of custom Enrichers. I did experiment briefly with middleware vs enrichers and they both seem to work as expected. Both always added the additional properties to all log entries. I'm still not quite sure I understand why the DiagnosticContext option behaves the way it does, unless it is simply due to the logging in question being in a SignalR hub as #Gordon Khanh Ng. posted. If that were the root of the problem though, you wouldn't think the enrichers or middleware would work either.

How to organize endpoints when using FeathersJS's seemingly restrictive api methods?

I'm trying to figure out if FeathersJS suits my needs. I have looked at several examples and use cases. FeathersJS uses a set of request methods : find, get, create, update, patch and delete. No other methods let alone custom methods can be implemented and used, as confirmed on this other SO post..
Let's imagine this application where users can save their app settings. Careless of following method conventions, I would create an endpoint describing the action that is performed by the user. In this case, we could have, for instance: /saveSettings. Knowing there won't be any setting-finding, -creation, -updating (only some -patching) or -deleting. I might also need a /getSettings route.
My question is: can every action be reduced down to these request methods? To me, these actions are strongly bound to a specific collection/model. Sometimes, we need to create actions that are not bound to a single collection and could potentially interact with more than one collection/model.
For this example, I'm guessing it would be translated in FeathersJS with a service named Setting which would hold two methods: get() and a patch().
If that is the correct approach, it looks to me as if this solution is more server-oriented than client-oriented in the sense that we have to know, client-side, what underlying collection is going to get changed or affected. It feels like we are losing some level of freedom by not having some kind of routing between endpoints and services (like we have in vanilla ExpressJS).
Here's another example: I have a game character that can skill-up. When the user decides to skill-up a particular skill, a request is sent to the server. This endpoint can look like POST: /skillUp What would it be in FeathersJS? by implementing SkillUpService#create?
I hope you get the issue I'm trying to highlight here. Do you have some ideas to share or recommendations on how to organize the API in this particular framework?
I'm not an expert of featherJs, but if you build your database and models with a good logic,
these methods are all you need :
for the settings example, saveSettings corresponds to setting.patch({options}) so to the route settings/:id?options (method PATCH) since the user already has some default settings (created whith the user). getSetting would correspond to setting.find(query)
To create the user AND the settings, I guess you have a method to call setting.create({defaultOptions}) when the user CREATE route is called. This would be the right way.
for the skillUp route, depends on the conception of your database, but I guess it would be something like a table that gives you the level/skills/character, so you need a service for this specific table and to call skillLevel.patch({character, level})
In addition to the correct answer that #gui3 has already given, it is probably worth pointing out that Feathers is intentionally restricting in order to help you create RESTful APIs which focus on resources (data) and a known set of methods you can execute on them.
Aside from the answer you linked, this is also explained in more detail in the FAQ and an introduction to REST API design and why Feathers does what it does can be found in this article: Design patterns for modern web APIs. These are best practises that helped scale the internet (specifically the HTTP protocol) to what it is today and can work really well for creating APIs. If you still want to use the routes you are suggesting (which a not RESTful) then Feathers is not the right tool for the job.
One strategy you may want to consider is using a request parameter in a POST body such as { "action": "type" } and use a switch statement to conditionally perform the desired action. An example of this strategy is discussed in this tutorial.

ASP.NET Core Application Insights - Track Authenticated User ID

I have read everything I could find, and everything suggests using ITelemetryInitializer. However, the best I can figure - that only runs once as its a Singleton. It also runs before the user has authenticated, so I don't have the data I need quite yet.
I have added the logic to my client side tracking as that was pretty straightforward:
#if (_userService != null && _userService.IsAuthenticated())
{
<script>
appInsights.setAuthenticatedUserContext('#_userService.GetCurrentUserId()');
</script>
}
Note in this case _userService is a DI service I use to access the currently authenticated user (which for now just uses ClaimsPrincipal).
What I need to do now is add the same setting to the server side telemetry, but I can't seem to figure out how to tie-in to it. Anyone out there figured this out?
So I guess this falls into the bucket of "as soon as you as StackOverflow you figure it out yourself".
I don't know what I did wrong, but I do know once I changed my initializer from implementing ITelemetryInitializer to implementing TelemetryInitializerBase, it started working.

Securing API keys in Nuxtjs

I've researched and found three different possibilities to solving my case: I'd like to make an async API call (using dotenv variables to store the credentials) and commit the returned data to Vuex on app init --keeping the creds secure.
Currently I'm attempting using serverMiddleware, but I'm having trouble accessing the context. Is this possible? Currently just getting a "store is not defined" error.
Also, after researching, I keep seeing that it's not a good idea to use regular middleware, as running any code on the client-side exposes the env variable... But I'm confused. Doesn't if (!process.client) { ... } take care of this? Or am I missing the bigger picture.
Additionally, if it does turn out to be okay to use middleware to secure the credentials, would using the separate-env-module be wise to make doubly sure that nothing gets leaked client-side?
Thanks, I'm looking forward to understanding this more thoroughly.
You can use serverMiddleware.
You can do it like this:
client -> call serverMiddleware -> servermiddleware calls API.
that way API key is not in client but remains on the server.
Example:
remote api is: https://maps.google.com/api/something
your api: https://awesome.herokuapp.com
since your own api has access to environment variables and you don't want the api key to be included in the generated client-side build, you create a serverMiddleware that will proxy the request for you.
So that in the end, your client will just make a call to https://awesome.herokuapp.com/api/maps, but that endpoint will just call https://maps.google.com/api/something?apikey=123456 and return the response back to you