View model with the authorization example - resolvejs

I want to restrict access to view models according to the authorization or JWT. I found examples for the read models, but how to implement it for the view models in the right way?

In resolve framework every view-model can have own serializer and deserializer. These functions are used for view-models which have non-trivial state object, which cannot be automatically serialized by JSON.stringify and be restored within JSON.parse - for example, it's useful for Immutable.JS or seamless-immutable.
In fact serializer has two arguments - first is state object for serialization, and second argument is JWT token from invoker. Since view-model is always had been invoked from current client, either HTTP request or API handler, JWT token is always present and can be used for access restriction
const serializeState = (state, jwtToken) => {
if(jwtToken != null && !isGoodToken(jwtToken)) { // JWT token is present and custom validation failed
throw new Error('Access denied')
}
return JSON.stringify(state) // Or custom serialize procedure
}
export default serializeState
Important notice: do not restrict serialized state access in case of jwtToken absence, since it used for internal purposes in snapshot adapters. Always allow return serialized state if second argument is undefined. Else if jwtToken present and invalid, error can be thrown to restrict access.

Related

Error when checking for custom claims property on rules auth token

I receive an error in the emulator when I try to check for a custom claim field that does not exist on the request.auth.token object when checking storage.rules. The request fails which is correct if the property is missing but I am concerned about the error.
function isPlatformVerified() {
return request.auth.token.platformVerified == 'ok';
}
and this is the error shown in the emulator:
com.google.firebase.rules.runtime.common.EvaluationException: Error: /Users/marcel/git/dev/storage.rules line [68], column [14]. Property platformVerified is undefined on object.
I wish to check if the custom claims has this property and if it has that it contains the correct value. How do I do this without getting an error (or can I ignore this??)
Many thanks
Most likely the custom claim hasn't propagated to the client and rules yet.
Custom claims are part of the token that the client sends with its requests, and that token is only auto-refreshed once per hour. So it may take up to an hour before a new claim shows up in the client, and thus in the security rules.
You can force a refresh of the ID token on the client by calling user.reload(), to ensure that the new claims will be present before the auto-refresh.

Second parameter in express route handler

I'm coming across code where there's an additional parameter for express route handlers beyond the path and the callback.
For example:
app.get('/path', authUser, (req,res) => {
...
}
where authUser is a function. Can anybody explain the role of such functions? To date I've only seen express routes with the two parameters.
These are middleware, which are functions that run before your route handler (your third function). You can have as many as these as possible. They basically modify/perform an action based on the request, or maybe manipulate the response.
So this is likely middleware that checks the request for an authenticated user, and will return a 401/403 if not authenticated, meaning that you can write your route handler under the assumption that you are authenticated.
For more info, check out this article
The family of methods such as app.get(), app.post(), app.use(), accept any number of request handlers as successive arguments:
app.get('/path', fn1, fn2, fn3, fn4);
These requests handlers can be used for a variety of purposes. Often times, they are what is generally referred to as middleware which prepares a request for further processing or in some cases blocks a request from further processing. But, they can also be normal request handlers too, they are not just limited to what most people call middleware.
In your specific case:
app.get('/path', authUser, (req,res) => {
...
}
We can guess by the name that authUser is checking to see if the user making the request has been properly authenticated and, if not, then an error status is probably sent as the response and the next request handler in the chain is not called. Or conversely, because authUser has already filtered out any unauthenticated users, the request handler here at the end of the chain can safely assume that the user is already authenticated. So, this particular use is a means of applying middleware to one specific route with no consequences for any other routes defined later.
But, I want to emphasize that this is a generic mechanism that is not limited to just what is classically described as middleware. It can also be used for request handlers that might execute conditionally based on other parameters. For example here's one such example where the first request handler looks the URL and decides to handle the whole request itself based on what it sees in the URL and, if not, passes it on to the next handler:
app.get('/book/:id', (req, res) => {
// check if id is purely numeric
if (/^\d+$/.test(req.params.id)) {
// this is a request for a book by numeric id
// look up the book numeric id in the database and return the meta
// data about this book
} else {
// not a book id, let next request handler have the request
next();
}
}, (req, res) => {
// must be a book title lookup
// look up the book in the title database and return the id
});

How to make CORS API call from Blazor client app with authentication using AutoRest Client?

I am trying to call Web API from Blazor Client App. The API sends required CORS headers and works fine when I call the API using plain Javascript.
The API needs Auth cookies to be included when making a call so using JavaScript I can call:
fetch(uri, { credentials: 'include' })
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log('Failed'));
Now, I am trying to do the same on Blazor. I came across this section on the docs which says:
requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = FetchCredentialsOption.Include
};
When I make a call now, it fails with following exception:
WASM: System.Net.Http.HttpRequestException: TypeError: Failed to execute 'fetch' on 'Window': The provided value '2' is not a valid enum value of type RequestCredentials.
I noticed that adding following on Statrup.cs allows me to call API including credentials (here):
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
{
WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
}
Now, I would like to call the API using AutoRest generated API Client so that I can reuse existing client and save lot of time. Setting DefaultCredentials as above doesn't work and shows following exception:
WASM: Microsoft.Rest.HttpOperationException: Operation returned an invalid status code 'InternalServerError'
Setting the requestMessage.Properties as above, says
The provided value '2' is not a valid enum value of type RequestCredentials`.
I am already injecting HttpClient from Blazor using this technique.
This is not really the answer... I just need space
Setting the requestMessage.Properties as above, says The provided
value '2' is not a valid enum value of type RequestCredentials
If so, what is wrong with the other method I suggested, which I guess is working.
Incidentally,
The provided value '2' is not a valid enum value of type
RequestCredentials
is not related to Blazor, right ? No such type (RequestCredentials) in Blazor. Perhaps your code, whatever it may be, gets the numeric value of the FetchCredentialsOption.Include and not its Enum string
Consider instantiating an HttpRequestMessage object, and configuring it according to your requirements.
Hope this helps...

aurelia-authentication OAuth2 response state value differs

I'm attempting an implementation of aurelia-authentication with an OIDC provider (IdentityServer4) and seem to be running into an issue with logging a user out.
The short of it is I'm not able to logout users successfully using the authService.logout function mentioned in the OIDC configuration section (https://aurelia-authentication.spoonx.org/oidc.html).
In looking into it a bit further I've tracked it down to a promise rejection in the logout function which provides the message: "OAuth2 response state value differs"
if (logoutResponse.state !== stateValue) {
return Promise.reject('OAuth2 response state value differs');
}
logoutReponse seems to be the culprit as it's coming through as an object with the state property named incorrectly {/login?state: "qAIxYwKqLHYJtyar2PfdvaROWT1O56P7"}.
I can actually change the if statement to:
if (logoutResponse['/login?state'] !== stateValue) {
return Promise.reject('OAuth2 response state value differs');
}
which seems to be working fine, but requires us to modify the aurelia-authentication source directly.
Any thoughts from anyone as to why the "state" property is coming through as a relative path instead of just "state"?
So after spending more time on this I was able to track the issue down and find a solution.
The solution was to change the aurelia-authentication authConfig postLogoutRedirectUri value to just the root page (http://localhost:8080). Additionally, I needed to define that URI under the PostLogoutRedirectUris within my IdentityServer4 Client definition.
logoutResponse was then coming through correctly with a property named state property that holds the correct value and permits the redirect successfully.

ServiceStack implemente CRUD on UserAuth table generated by Authentication

I'm trying the built-in Authentication of ServiceStack. My approach is 'OrmLiteAuthRepository' so users' information are stored in Sql Server instead of the default in memory storage. I use Postman to test the endpoints.
My target is receiving user rows, updating user information, creating users, deleting an user row. Those are the endpoints I found in Postman after importing (I didn't create those endpoints):
GET 'http://localhost:47391/api/register',
PUT 'http://localhost:47391/api/json/reply/Register'
POST 'http://localhost:47391/api/json/reply/Register'
I tested POST, Sql Server automatically created the tables to store user data. And the data could be written into Sql Server so I have no problem with POST.
But with PUT, isn't it for updating the existing row? I append '/{id}' to the end. But it created a new row in the database instead of updating the existing one. How does it work?
With GET, I got no implementation error.
{
"ResponseStatus": {
"ErrorCode": "NotImplementedException",
"Message": "Could not find method named Get(Register) or Any(Register) on Service RegisterService",
"StackTrace": " at ServiceStack.Host.ServiceExec`1.Execute(IRequest request, Object instance, Object requestDto, String requestName)\r\n at ServiceStack.Host.ServiceRequestExec`2.Execute(IRequest requestContext, Object instance, Object request)\r\n at ServiceStack.Host.ServiceController.<>c__DisplayClass11.<>c__DisplayClass13.<RegisterServiceExecutor>b__10(IRequest reqCtx, Object req)\r\n at ServiceStack.Host.ServiceController.ManagedServiceExec(ServiceExecFn serviceExec, IService service, IRequest request, Object requestDto)\r\n at ServiceStack.Host.ServiceController.<>c__DisplayClass11.<RegisterServiceExecutor>b__f(IRequest requestContext, Object dto)\r\n at ServiceStack.Host.ServiceController.Execute(Object requestDto, IRequest req)\r\n at ServiceStack.HostContext.ExecuteService(Object request, IRequest httpReq)\r\n at ServiceStack.Host.RestHandler.GetResponse(IRequest request, Object requestDto)\r\n at ServiceStack.Host.RestHandler.ProcessRequestAsync(IRequest httpReq, IResponse httpRes, String operationName)"
}
}
How to implement it? I assume I consider the user a normal Web Service entity? and create 'UserService', and requests like:
[Route("/register")]
public class User : IReturn<UserResponse>
{
...
}
BUT there isn't a model class like 'User' due to the tables are created by ServiceStack itself, how to solve this?
Or is there something I am not aware of. Thanks.
The error message:
Could not find method named Get(Register) or Any(Register) on Service RegisterService
Is saying you're trying to call the built-in ServiceStack Register Service instead of your Service. But the Register Services isn't enabled by default, your AuthFeature likely explicitly enables it, either with:
Plugins.Add(new RegistrationFeature());
Or on the AuthFeature:
Plugins.Add(new AuthFeature(...) {
IncludeRegistrationService = true
});
If you don't want to enable ServiceStack's built-in Register Service you'll need to remove the registration where it's enabled.
If you instead want the Register Service registered at a different path, you can specify a different route with:
Plugins.Add(new RegistrationFeature {
AtRestPath = "/servicestack-register"
});