How to set an identity provider "middleware" in NestJS? - nestjs

I'm giving NestJS a try and am pretty happy with the results so far. Right now I'm struggling with some concepts that aren't clear enough in my head.
My API has an authorization-token in the format of a cookie (NOT A JWT). When the API receives a request, it has to use said cookie to ask another service (async), which user is sending it and what role he has.
This exchange from cookie to user info should prepend any controller logic and should be applied globally.
I think this can be done via a middleware, an interceptor or a pipe, but which of those is considered the better way according to NestJS?

Honestly, I would use a guard for this kind of feature. Check if the cookie exists, if not, there's already a problem, send back a 403 (i.e. return false). Otherwise, the rest of the logic can follow and you can attach the information to your req object, thereby having it available throughout the rest of the request. As guards are the first of the enhancers to fire, this also ensures that the value is available in interceptors and certain pipes.

Related

What is the best way to combine a GET and POST method in a middleware api?

I have to create a middleware API which a functionality to check for a key present in my database. If the key exists then it should simply fetch it(GET method). If not, then the API should create the key and its value in the database and return that(POST method). So since we have 2 fundamentally different methods being combined in this API, is it correct to do so? What should be the best way to design such API?
Don't combine them.
Return zero results from your GET method if you the record doesn't exist. Then in the client, if you receive zero results, POST the needed information to another API endpoint.
Combining the two ideas into one will create a hard to understand system. Your system should be deterministic, i.e. you can always know the result of every call before you call it.
One way to look at your API is to forget about the underlying database, but think about how an API client uses it.
If an API client does a GET request, 2 things happen:
The existing record is returned
A new record is created and is returned
A client might not actually care if 1 or 2 happened. For the perspective of the client, it might look like the resource always existed (even if it was technically just created).
So as long as there's no extra information that must be sent along with a POST request, it might be fine to use a GET request for both cases.
I don't know about your situation, typically it is best to have your get and post seperated. Though, if your client thinks that it needs to create a record and then posts the data, i dont see the problem with returning the resource and a 409 for the resource already existing. Here is a similar question HTTP response code for POST when resource already exists
Then the client can handle the 409 differently or the same as a 200 depending on your needs.

How do I pass multiple parameters (or pieces of information) through state with Stripe

Stripe has a state parameter that it returns back to me to verify
https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_ABCDEFG12345&scope=read_write&redirect_uri=https://sub2.example.com&state=asdf1234
Which is great! But what if I want to get a few things back from Stripe when it returns? Can I pass multiple pieces of information to this parameter? Is the best way to do this by stringifying and object and then parsing it when it is returned?
Great question! By design you should not pass serializable data through an OAuth2 state parameter, as it leaves open a window where a malicious party could edit that data before it's returned to your application. You should use your own application's authentication state to verify your users' identity once the Stripe OAuth flow returns to your site.
It's recommended that you use 'state' as a CSRF protection, and pass any sensitive parameters through your own application:
https://stripe.com/docs/connect/reference#get-authorize

Making authenticated requests

I am using form authentication and role based access.
I want to make all the subsequent request as an authentication request using the access token.
I refer Loopback-example-access-control example, but not get a clear idea.
In this example, they pass access token using query string. My question is I want to make all the request as authenticated using access-token without pass query string or header.
Any other alternative way is available?
I need demo application that includes authentication and authorization, except loopback-example-access-control example.
Please help me, I am new to strong loop.
There are only three ways to send data to a server: path/query string, headers, and the request body. Since you don't want to use the query string (which is good, you really shouldn't) and you don't want to use a header (which is the most common and currently the industry standard) then you are left with only the request body. That's not a great choice either, and not supported by default in LoopBack, you would have to code that up yourself.
The right solution here is to use the Authorization header and send the access token in there with each request.
And just to be clear, this really has nothing to do with LoopBack, this is just token-based authentication basics. You must pass the token with each request, that's how the system works, there is no alternative.

REST with complex permissions over resources

Background
I'm having a trouble with the design and implementation of a REST service which publishes content that some users cannot view (medical information, you know, country's laws), I'm using a ABAC-like/RBAC system to protect them, but what causes me concern is that I may be violating the REST pattern. My services does the following process for each query:
The security middleware reads a token from a session that an app/webpage sends using authorization header or cookies.
ABAC/RBAC Rules are applied to know if user can access the resource.
After authorize the token, my service executes the query and filters the results, hiding content that requesting user cannot see (if needed. POST, PUT and DELETE operations are almost exempt from this step). The filter is done using ABAC/RBAC rules.
An operation report is stored in logs.
I already know that sessions violates REST pattern, but I can replace it using BASIC/DIGEST authorizations. My real question is the following:
Question
Does hiding resources from list/retrieve operations violates REST pattern? As far I know, REST is stateless, so ... What happens if I use some context variables to filter my results (user id)? Am I violating REST? Not at all?
If I do, What are your recommendations? How can I implement this without breaking REST conventions?
First of all, client-side sessions don't violate REST at all. REST says the communication between client and server must be stateless, or in other words, the server should not require any information not available in the request itself to respond it properly. If the client keeps a session and sends all information needed on every request, it's fine.
As to your question, there's nothing wrong with changing the response based on the authenticated user. REST is an architectural style that attempts to apply the successful design decisions behind the web itself to software development. When you log in to Stack Overflow, what you see as your profile is different from what I see, even though we are both using the same URI, right? That's how REST is supposed to work.
I'd recommend returning status codes 401 (Unauthorized) if the user is not authorized to access a resource. And 404 (Not found) if you cannot confirm that the resource even exists.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
A GET is meant to return a representation of the resource. Nowhere does it say that you must return everything you know about that resource.
Exactly what representation is returned will depend on the request headers. For example of you might return either JSON or XML depending on what the client requested. Extending this line of thinking; it is ok to return different representations of a resource based on the client's authentication without violating REST principals.

Mixing Service-Oriented Architecture Security and Business Logic

I have a SOA which makes heavy use of nonces (i.e, one-time one-use security tokens).
My app takes a nonce from a client, verifies it, then sends a new nonce back to said client as part of every reply. Also included in each reply are the results of business logic operations that executed right after the nonce was authenticated.
The nonce verification and generation are operationally coupled with the business logic, since both occur in response to every client request. However I don't want the two to be coupled in code. What's the right way to partition them in accordance with SOA principles? Is it too much to break the security and business logic into two separate services, with one calling the other as part of each reply to each client request?
Yes it makes sense to separate them. But I don't think they should have awareness of each other at all (Call each other directly).
I'll dive into a specific example and technology of how something similar is implemented.
In the web frame work Struts2 all incoming requests pass through a stack of operations(called interceptors) before arriving at a user defined object (called an action). The action then will access the business tier.
When submitting a web form there is the issue of double submission. So one way to protect against this is with a token that is sent along with the form submission. So we need to create a unique token place it as a hidden field, and then when we receive the request only process it if the token is good. This prevent users from doing something like accidentally buying something more than once.
In Struts2 there is a special server side token tag which creates the hidden field for us. So there is something that needs to be done for each form. The token interceptor if active will enforce that this value always exists and is good when receiving the form and will redirect responses that do not somewhere else.
The idea of implementing a nonces interceptor/filter that checks that the incoming nonce value is good and for responses adds the correct nonces value to the response should be completely independent of the business logic.
The example here is with html forms but adding an interceptor(or whatever you call "that which handles cross cutting concerns at the request/response level" for your appropriate technology) which adds such a value to json or xml messages should be pretty easy and likely produce the most elegant result.
The following is a link to struts2 interceptor reference (it might clarify the idea better):
http://struts.apache.org/2.2.1.1/docs/interceptors.html
The following two links are both interceptors which manage tokens:
http://struts.apache.org/2.2.1.1/docs/token-interceptor.html
http://struts.apache.org/2.2.1.1/docs/token-session-interceptor.html
I expect only the first few paragraphs of each link will be useful but something like it for your technology should be nice.
I think what you outlined above would be in keeping with SOA principles. You're keeping two distinct sets of operations separated - once service has the business logic, the other has the security logic.
This would be especially true if you have (or the potential of having) other services that would rely on nonces.

Resources