Is it better to get ID from URL or JWT in an authenticated API - api

So I am creating some api's on Laravel using Passport (JWT).
I am having issues deciding what is the preferred method for the following:
PUT: api/users/{user_id}
PUT: api/users/me
I need the api so that the user can change his own information, but I would also like it for the api to be accessible for the Admin to change said information.
At the moment I am only using the first API and checking if the ID is the same as the one in the JWT auth or if the one requesting the api is the Admin.
But I was also thinking that maybe it was better to have them separate. The first api should only be accessible to the Admin, and I should be taking the ID from the JWT auth for the second api.
What would be the correct choice? Or is there a better choice?

I would say using this approach is better:
PUT: api/users/{user_id}
That allows anyone to consistently link to your own profile or to some other user profile in the same way. Then depending on your authentication and authorization, you can be allowed to do different operations on that resource.

There is no correct or better choice. You seem to understand the implications of using any of them so it's really up to you to choose. With the /{user_id} version you have to be extra careful not to remove proper validation rules from your code. If you used /users/me for a GET operation you would have to be careful with setting cache headers. If a browser would cache a response to users/me and then another user would request this endpoint, then you could get some other user's data. For PUT operations, though, this is not a concern.

Related

Handling authorization with IdentityServer4

I'm extremely confused on how to use a centralized IDP with both authentication and authorization. The architecture for my project was to be a single web API and one React client. I wanted to keep things structured out into microservices just to try something more modern, but I'm having major issues with the centralized identity, as many others have.
My goal is fairly simple. User logs in, selects a tenant from a list of tenants that they have access to, and then they are redirected to the client with roles and a "tid" or tenant id claim which is just the GUID of the selected company.
The Microsoft prescribed way to add identity in my scenario is IdentityServer, so I started with that. Everything was smooth sailing until I discovered the inner workings of the tokens. While some others have issues adding permissions, the authorization logic in my application is very simple and roles would suffice. While I would initially be fine with roles refreshing naturally via expiration, they must immediately update whenever my users select a different tenant to "log in" to. However, the problem is that I cannot refresh these claims when the user changes tenants without logging out. Essentially, I tried mixing authorization with authentication and hit a wall.
It seems like I have two options:
Obtain the authorization information from a separate provider, or even an endpoint on the identity server itself, like /user-info but for authorization information. This ends up adding a huge overhead, but the actual boilerplate for the server and for the client is minimal. This is similar to how the OSS version of PolicyServer does it, although I do not know how their paid implementation is. My main problem here is that both the client and resource (API) will need this information. How could I avoid N requests per interaction (where N is the number of resources/clients)?
Implement some sort of custom state and keep a store of users who need their JWTs refreshed. Check these and return some custom response to the caller, which then uses custom js client code to refresh the token on this response. This is a huge theory and, even if it is plausible, still introduces state and kind of invalidates the point of JWTs while requiring a large amount of custom code.
So, I apologize for the long post but this is really irking me. I do not NEED to use IdentityServer or JWTs, but I would like to at least have a React front-end. What options do I have for up-to-date tenancy selection and roles? Right when I was willing to give in and implement an authorization endpoint that returns fresh data, I realized I'd be calling it both at the API and client every request. Even with cached data, that's a lot of overhead just in pure http calls. Is there some alternative solution that would work here? Could I honestly just use a cookie with authorization information that is secure and updated only when necessary?
It becomes confusing when you want to use IdentityServer as-is for user authorization. Keep concerns seperated.
As commented by Dominick Baier:
Yes – we recommend to use IdentityServer for end-user authentication,
federation and API access control.
PolicyServer is our recommendation for user authorization.
Option 1 seems the recommended option. So if you decide to go for option 1:
The OSS version of the PolicyServer will suffice for handling the requests. But instead of using a json config file:
// this sets up the PolicyServer client library and policy provider
// - configuration is loaded from appsettings.json
services.AddPolicyServerClient(Configuration.GetSection("Policy"))
.AddAuthorizationPermissionPolicies();
get the information from an endpoint. Add caching to improve performance.
In order to allow centralized access, you can either create a seperate policy server or extend IdentityServer with user authorization endpoints. Use extension grants to access the user authorization endpoints, because you may want to distinguish between client and api.
The json configuration is local. The new endpoint will need it's own data store where it can read the user claims. In order to allow centralized information, add information about where the permissions can be used. Personally I use the scope to model the permissions, because both client and api know the scope.
Final step is to add admin UI or endpoints to maintain the user authorization.
I ended up using remote gRPC calls for the authorization. You can see more at https://github.com/Perustaja/PermissionServerDemo
I don't like to accept my own answer here but I think my solution and thoughts on it in the repository will be good for anyone thinking about possible solutions to handing stale JWT authorization information.

Simple RESTful API authentication

I'm building a single-page web application, fully based on RESTful API. I've seen several topics in that matter, but some things remain unclear for me.
I will need users to log in. Here are some of my ideas:
I can send e-mail and password to API and use basic auth. I'm not sure where should I keep password, should it be encrypted and if so: how?
Can I use built-in session system instead? Is it wrong to use cookies directly in the RESTful API? Why is it so popular to send credentials/keys to API itself instead of using cookies?
I thought about having one API key per user, return it in login action and keep it in localStorage. I guess it's not the greatest idea to have just one key per user?
Then, I came up with idea to have separate keys table and add random keys each time somebody logs in. On logout, the key would go away and no longer be valid. This is more secure than previous idea.
How is it solved in simple projects? I'd like to make it simple but not ridiculously inserure.
Please help.
The commonly approach is to use the header Authorization in REST. The state of the application must be on the client side with REST and shouldn'a be tied to a particularly client kind (browser with cookies)
I think that this link could be helpful:
Implementing authentication with tokens for RESTful applications : https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/
There is also à great question to à similar question here : https://softwareengineering.stackexchange.com/questions/141019/should-cookies-be-used-in-a-restful-api
Hope it helps,
Thierry

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

RESTful way of having a single resource based on authentication

I have an API that provides an Account resource based on the authentication (login) that is supplied. As a user can only have one account, and can only see it's own account and not those of others, this API will basically be a single resource API in all cases.
So to keep things simple, I have this resource under the url accounts/ and when you access accounts/?username=dude&password=veryhard you'll get your account data (if you dohn't supply authentication you'll get a 403).
Now I wonder if this is RESTful. Also, you should be able to update your account info, and I wonder if PUT would be appropriate. In my knowledge, PUT should be done on a unique URI for the resource. Well, is this a unique URI for the resource? Generally a URI for an account would look like accounts/3515/ where 3515 is the account id. However, users don't know their account id. Also, there should be more ways to log in, instead of a username + password you should also be able to use a token (like accounts/?token=d3r90jfhda139hg). So then we got 2 URL's that point to the same resource, which also isn't really beautiful for a RESTful URI, is it?
So, what would be the most RESTful solution? Or should I not do this RESTful?
REST purists will consider that use of /accounts/ to obtain a single account is bad practice as it should specify a collection. Instead consider a key which cannot be mistaken for an ID, for example if your IDs are UUIDs then use a token such as 'me' so your URL is /accounts/me. This has the advantage that if later on you wish to obtain different account information, say for example you need to list users or you have an administration system using the same API, then you can expand it easily.
Putting username and password in the URL is also not pure REST. The query parameters should be directly related to the resource you are obtaining; commonly filtering and limiting the resources returned. Instead you should seriously consider using something like HTTP Basic authentication over an encrypted (HTTPS) connection so that you separate out your authentication/authorisation and resource systems. If you prefer to use a token system then take a look at oauth or hawk.
Finally, yes if you use PUT you should supply a full resource identifier. Given that it is very common for systems to read data before updating it the lack of ID won't be a problem as that will come back as part of the prior GET.
Yes accounts/?username=dude&password=veryhard is a correct REST URL.
PUT is used with an id if it used to update a resource, if you use it to create you must supply an ID. otherwise you use post to create a resource without id

Flask login mechanisim to authenticate per token my calls

Hi I was looking at flask-login at handles the session login nicely, this work good for templating and views where I have access to the session.
Nevertheless I have been trying to know if there is a way I can send a user_token to authorized a call. I looked at the documentstion and is very vague regarding this. It said that I should
Implement get_auth_token in my User object.
Decorte a #user_loader function that can load the user token base.
I have though seen the following (please correct me If I am wrong)
Cookie base to store the auth token is there a way I can decide to send the token as part of the parameters, body or in the headers insteado having to get it from the cookie.
I am not quite sure how to authenticate a call with auth token.
I got a Way better approach that fits better my needs. Basically I extends LoginManager pretty easy and straighfoward if you take a look at the source of flask-plugin you come to realize that there is a call that is made #before_request there is a method called reload_user, this is the what I end up doing
class CustomLoginManager(LoginManager):
def reload_user(self):
if request.headers.has_key('Authorization'):
ctx = _request_ctx_stack.top
ctx.user = User.get(token=request.headers['Authorization'])
return
super(CustomLoginManager,self).reload_user()
If in my header I pass an authorization key then I will try to load using this key instead of session based approach, of course I am going to need to add more security layer to this approach proably by signing the key but overall this was what I needed.
Thanks all.
BTW you can override a bunch of others method and I highly recomend to take a look at the plugin source, so you can understand more deeply what it does 644 lines of codes worth reading
https://github.com/maxcountryman/flask-login/blob/master/flask_login.py
It seems like you're wanting something like OAuth instead of using Flask-Login. In case you don't know (quoted from Wikipedia), OAuth is a protocol that utilizes tokens in order to access resources on behalf of a resource owner. Think giving a user the ability to give out a valet key to certain portions of your site. Many sites, such as Google, Facebook, and Twitter use OAuth for authenticating third party clients in order to access certain user resources.
Right now, there's a split between the less flexible and less complex OAuth 1.0a and the more flexible but more complex OAuth 2.0. Many libraries exist for OAuth 1.0a in Python, but fewer for OAuth 2.0. However, there is a selection of those for OAuth 2.0 if stability isn't a top concern right now.
For the client, Flask-OAuth is available if you're going with OAuth 1.0a, and it is maintained by Armin, the Flask creator itself, so you can feel assured that it won't die. For the provider, there's an extension called Flask-OAuthProvider with OAuth 1.0a support. If you don't mind integrating it yourself and want 2.0 support, pyoauth2 provides you with both a client and a provider, though it looks less maintained.
Hopefully this helps you with exploring one possible avenue to utilize auth tokens, albeit without using Flask-Login. In my opinion, one shouldn't re-implement a protocol unless they understand it, so I recommend reading up about OAuth even if you decide not to use it. Many great articles exist on it, such as this article from Google and this one, too.
Just as an update, Flask-Login now has a 'header_loader' function, which can be used in conjunction with the standard 'user_loader'. Taken directly from the docs:
#login_manager.header_loader
def load_user_from_header(header_val):
if header_val.startswith('Basic '):
header_val = header_val.replace('Basic ', '', 1)
try:
header_val = base64.b64decode(header_val)
except TypeError:
pass
return User.query.filter_by(api_key=header_val).first()
Here's the link to the section in the Flask-Login docs