What error to handle first on a rest resource? - rest

I'm developing a REST API and when developing the user resource I ended up having a doubt. I want the users in my application to view other user profiles without being authenticated. But, obviously, a user needs to be authenticated to edit or delete his profile.
My doubt comes when I access, for example, to this url without been authenticated: PUT /api/user/1. Imagine that the user doesn't exists. Which error is checked first, the 404 because the resource does not exist or the 401 because the user is not authenticated? Thanks.

There's no point in querying for that particular user, if the request is a PUT and the current user isn't even authenticated. You'd be better off filtering these requests as soon as they hit your endpoint, and return a 401.

Related

How do I use Discord OAuth2 for user management and authentication in my application?

I'm building an application where I want to be able to create and authenticate users using Discord and OAuth2. The reasons are:
The application can be considered a "companion" app to a Discord community I am running, and
I don't want the users or myself to have to deal with usernames and passwords
The application consists of a client desktop application and backend services. I have a fairly basic understanding on how I authorize the user with Discord:
Client application goes to backend endpoint /oauth/login and the user is redirected to the Discord app approval page
The user confirms and is redirected to the backend callback /oauth/callback with a code that can be used to fetch a pair of access and refresh tokens.
Frankly, from this point I am kind of stumped on how the rest of the authentication should work. I assume at least the following:
I need to create a user entry in my database with at least an UID (for simplicity the same as the one for the user in Discord), the access and refresh token pair. If user is already created, update the database with the new tokens.
Whenever the application needs user information from Discord it should use the access token. If it has expired, exchange the refresh token with Discord to get a new token pair.
But now what? This only authenticates the user against Discord. I want to leverage the fact that the user is authenticated with Discord to be authenticated to my application. Here are some general questions I have:
Do I make a new token for the user to use for subsequent requests to my backend endpoints? Or do I return the Discord access token to the desktop client?
What do I do when the token expires? Do I also need a "exchange" endpoint for the desktop client to refresh the token (possibly that just forwards to Discord to get a new token, depending on the answer to my previous question).
This all feels like it should be very basic, but I am out of my comfort zone here and need some help to be unblocked.
Thanks for reading!
Your own application should effectively have its own session system.
The easiest is likely to just use HttpOnly cookie-based sessions, which something like a Redis store (or Memory store if this is a toy project).
The session data on the server should contain information on which user is currently logged in. You should probably store the discord access and refresh token in a database.
The simplest way to deal with refreshing, is to simply call their refresh token endpoint as soon as you get a 401 response. If discord provides information on how long access tokens are valid, you could also preemptively refresh instead of only doing this when you get the 401. Your server does the refreshing, you don't need an endpoint for this.
Generally I can recommend that your server handles all interactions with the discord API, and never your client. (aside from the initial authorization step).

Oauth2: authorize access based on unguessable url in email

Our application uses oauth2 & openid connect for auth&auth. It's built using an angular client that calls a REST API. I would like to know how to authorize access to the API, based on the possession of an unguessable url.
I'll explain this a little more. In the application, a user can invite another user. When this happens, an email is sent to the second user. When user 2 clicks a link in the email, he is sent to a webpage with details about the invitation.
Only user 2 should be allowed to see the invitation page. I was planning to solve this by using an 'unguessable url' in the email. Upon visiting the url, the user must somehow be authorized to fetch the invitation details from the API.
The question: how do I authorize a user, based on knowing the unguessable url? How do I assign a claim when the page is loaded, and how do I verify this claim in the API call that follows? The only solution I see, is to set a cookie containing a token. But this is not in line with our existing auth mechanism. I prefer not writing my own token validation code, and let the Identity Provider handle this.
Additional info: user 2 may or may not have an account in the system, and he may or may not be logged in. Neither should prevent the user from seeing the invitation details. In other words: a totally unknown user should be able to see the page. The knowledge of the url should be the only requirement.
Any solution to this problem? Or am I handling it all wrong?
After asking around, the general consensus is to NOT let the external auth mechanism take care of this, but to validate the link ourselves.
The solution is to turn the unguessable part of the url (the 'link id') in some kind of token, which can be validated upon calling the API. This is done by the API itself, not by the Identity Server.
Applied to the invitation issue: when an invitation is created, store the link id together with some info, i.e. what kind of access it allows (invitation access) and the id of the invitation. When the user calls the API to get the invitation, pass the link id for validation. Match the invitation id with the invitation id stored in the link, and if it doesn't, throw an error.

HTTP status to return after trying to logout without being logged in

Suppose I have a RESTful authentication endpoint:
http://example.com/api/v1/auth
A POST request with email and password allows for logging in. A request gets countered with a response with HTTP 200 for correct login or 403 for incorrect.
A DELETE request allows for logging out.
It's obvious that after a successfuly logout I should return HTTP 200. What HTTP response code should I return, if a user tries to logout without being logged in?
It's obvious that you should return status 200 for successful logout? Not at all. If you don't return a response with that status, then 204 or 205 would be more appropriate (205 = "no content, refresh"), since there is no content to return, and the client should probably refresh its view.
If the user wasn't logged in: Think about what a client would think about it. Either the client wasn't aware that the user wasn't logged in. Or the client wasn't sure whether the user wasn't logged in, and logged out just in case. After the call, the user is logged out. What purpose would it serve to give a different status than for a formerly logged in user? Even if the client detected such a status correctly, what is there that the client could usefully do?
I'd give the exact same response. Don't see it as "I was logged out", see it as "I am not logged in". If you really want to report it, return status 200 with a different content for users that were logged in and users that were not logged in.
The short answer to your question is 404. Here's why: DELETE means "delete the resource identified by the URL," so a successful request to DELETE /api/v1/auth should delete whatever /api/v1/auth identifies, causing subsequent requests to DELETE /api/v1/auth to return 404 Not Found.
The problem with DELETE is that, ideally, /api/v1/auth, like any other URL, should represent the same resource regardless of whether the current user is logged in or not and regardless of the identity of the logged-in user; so if one user asks the server to DELETE this resource and receives a 2xx response, any subsequent request, by any user, to POST /api/v1/auth (logging in) or DELETE /api/v1/auth (logging out) should fail and return 404.
Therefore I think it's better to implement both login and logout by POSTing to two different resources, e.g. /api/v1/auth/login and /api/v1/auth/logout.

django rest framework - understanding authentication and logging in

I am a beginner to django rest framework (and to REST in general) and I have a server side which (for now) has a UserViewSet which allows to register new users and I can POST to the url from my android app just fine (I get 201 CREATED).
I read a lot about it, but I don't seem to fully the understand the concept of Login and Authentication in REST frameworks and specifically in django rest framework, and how it works.
Do you "Log in" (like in facebook for example) and then you can make requests?
What I understand\heard off:
you can Login to a API\website using your username and password (assuming off course that you have registered as a user and you are in the user database).
After you are Logged in - you will be able to make requests to views that allow access only to logged in\authenticated users.
Is that somewhat correct? I mean, is there a "Log in" url where you login and that's it? you are authenticated?
Also read somewhere that there isn't actually a login url, and you have to add your username and password to each request and then the request has to check if your details are in the User database?
To sum up, I am not really sure how does authentication/logging in (same thing?) happens in django REST framework... and would really appreciate a good explanation or an example..
Thanks a lot!
In a normal web application (removing the API from the question), a user would "log" in with their credentials (username/password, social tokens, etc.) and would receive a session cookie (assigned by Django) that allows them to authenticate in future requests on behalf of a user (realistically, themselves). This session cookie stays on their system for a limited period of time (two weeks by default) and allows them to freely use the website without authenticating again. If the session cookie needs to be removed, such that the person can no longer authenticate, the web application typically destroys the session cookie (or clears the session) which effectives "logs them out".
In the case of an API, it all depends on how the authentication works.
SessionAuthentication works just like as described above, as it uses Django's internal session system.
TokenAuthentication remembers the authentication information through a database-backed token (which is transmitted in the Authorization header) instead of a session cookie.
BasicAuthentication authenticates on every session (no persistent session) by passing the username and password on every request (base64 encoded through the Authorization header).
Other authentication methods generally work in the same way as TokenAuthentication.
So, here are some answers to specific questions which were raised
Do you "Log in" (like in facebook for example) and then you can make requests?
Using BasicAuthentication, you "log in" on every request by providing your credentials. With token-based authentication (TokenAuthentication, OAuth 2, JWT, etc.), you "log in" to receive the initial token and then your authorization is confirmed on every request.
Also read somewhere that there isn't actually a login url, and you have to add your username and password to each request and then the request has to check if your details are in the User database?
This is basic access authentication which you can use in DRF using the BasicAuthentication class.

How to authenticate without hitting the database?

A comment below an answer about state and REST recently piqued my interest. For clarity I'll quote the comment in full:
Nothing in my answer implies a solution based on database access on every request, if you think it does, it is a failing on your part to understand authentication and authorization at that scale. The authentication can be implicit in the state, do you think that facebook does a "database access" on every request of its REST API? Or Google for that matter? hint: no
I tried to think how one might authenticate without checking a user-provided value against a centrally-held one, even if one to know what data to display to the user, and came up blank. i freely admit this is a failing on my part to understand authentication and authorization at that scale. My question is therefore: how do sites like Facebook and Google accomplish this?
One way is claims based authentication. Simplified and somewhat loosely interpreted, it boils down to this;
Instead of the server application authenticating the user itself, an un-authenticated user is redirected to a separate authentication server.
The authentication server validates the user in any way it wants to (login+password, certificate, domain membership etc) and creates a signed "document" with the relevant user info (user id, name, roles, ...) It then redirects the user back to the server application with the document enclosed.
The server application validates the signature of the document, and if it trusts the signature, it can use the document contents to assume who the user is instead of accessing the database.
Normally, the server application caches the document in a cookie/session or similar so that the next access to the application does not have to bounce through the authentication server.
In this way, the server application does not need to concern itself with how the user is authenticated, just whether it trusts the judgement of the authentication server. If the authentication server (and possibly the client unless it's a browser) adds Facebook login support, the server application will automatically "just work" with the new login type.