How to identify the user is active in REST webservice java? - rest

I am using a REST in Java and also I am using a token system for that. I need to know that, how we need to maintain the user session? Since REST is stateless we can not maintain user session, then how we need to find the active user in server side?

After user is authorized and given access to the REST API a kind of a token or cookie should be returned with authorization response. The obtained token should be added all subsequent requests that need authorization. Using this token and assuming it's in one-to-one relationship with user you can easily identify the user.

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).

Restrict front client connexion with groups / roles in a realm

I'm looking for a way to restrict user access to specific clients in a realm.
I know I can do it with client where Authorization is enabled (fine-grained authorization support) but it doesn't work when trying to connect from front (client need to be public and not confidential).
I'm using a javascript application to login from front-end.
Is there a way to enable Authorization for public client or a work around ?
Thanks.
I'm not sure if this will totally answer your question because it's still not specific enougth but it may give you some further help.
In case you're new to the topic, please see difference between public and confidential clients here.
The current best practice for public clients like HTML/Javascipt applications is to use OpenId Connect with the Authorization Code Flow + PKCE. HTTPS is of course a must have. I recommend you use a javascript openid connect adapter for this like the following for example:
https://github.com/panva/node-openid-client
Basically your authentication / authorization flow is shown here:
When the user wants to login from your frontend client application first a unique verifier is generated which is only available to the exact user / browser session. This value get's hashed as a code challege. Then the user gets redirected to the login page of your authorization server (Keycloak for example) passing some parameters like a redirect uri and the challenge.
With successful login the user get's a session at the keycloak server which also stores the hashed challenge. Then the user gets redirected to given redirect uri (a path in your application) together with a code to obtain an access token. Back in your application you application uses the original value together with the code to get the actual token. The authorization server ckecks the value against the stored challenge and geturns the access token if it matches. You see the extra verifier is to prevent that anybody compromises your code fragment to obtain a token on your behalf.
Now you have an encoded access token in your browser app. Note the token itself is normally only encoded not encrypted but it can be signed. Those signatures can later be used from your backend to ckeck the token integrity but we will come to that soon. Roles, claimes, scopes and so on included in your access token tell you the privileges of the user/identity. You can of course use them to enable/disable functions in your app, block routes etc. but in the end client protection is never really effective so your real authorization ande resource protection happens at your resource server which is your backend (node, .net core, java etc.) maybe a restful Web Api. You pass your access token as a part of the http request header with every request to the backend. Now your backend checks the token integrity (optional) expiration time etc. analyzes scopes, claimes and roles to restrict the resource access.
For example a simple GET myapi/car/{1} may only need a token or can even be annonymous while a POST myapi/cars or PUT myapi/car/{1} may need a special role or higher privileges.
Does that help you out?

Call REST API with and without user context

I have a user microservice. This microservice uses token authorization. Now it's consumed by web application. Workflow looks like this:
user logs in to web application using AzureAd OpenIdConnect;
web application receives access token (authorization code flow);
web application gets user details from user service passing access token in HTTP request header.
Also I have a daemon microservice where I don't have a user context. I want to allow this daemon service to get user details from user service too. I'm going to use client credentials flow for that case.
How to organize user service rest api properly?
I'm thinking about this approach:
user's data is available at this URL /users/{userId}/info;
applications with user context (i.e. access token is issued for particular user using authorization code flow) can consume data only for current user or current user is an admin and can work with another user's data;
daemon applications without current user (i.e. access token is issued for the application itself using client credentials flow) can read data for any user.
What is the best practices for such cases?
I think the best and more restful approach to define this API is to build a unique endpoint /users/{id}.
Where id can be an actual real user id or a predefined value like 'me'. It is the user service the one who has to retrieve from the token the user information in case that the id value is 'me'.
The other changes that I would make is to use users instead of user because rest good practices say that the elements in the URL are collection.
And the last one, to not use info because it is redundant. Because when you query for an entity obviously you want its info

Limit user access to api calls?

I am creating a rest api to be the backend for a messaging app. I want a user to only have access to their own data. For example user1 can call /users/user1 but not /users/user2. How would I go about doing this.
So first the user will login and be authenticated via their username and password. But where do I go from here? I was thinking of storing a token with the users data so when they access it I can verify that the pair matches but there must be a better way to do this. Do I need to restructure my api?
After the user logs into the system, you should provide them a token or initialize a session for that user. In each consecutive call, the user should send the token to the API. As long as the token/session is alive user should be able to call the API.
You should have a way to verify the user token in the backend for each API call. A very popular way of doing this is to use JWT(JSON Web Tokens) based authentication.
See here for an example using python and flask: https://realpython.com/token-based-authentication-with-flask/
Once you verify the user, you should parse the user id to the database query in order to filter out the data for that user.
Even though I don't understand your full use case, it seems like you need to restructure your API calls as well. You should not provide API calls per user. What happens when the numbers of users increase in your system dynamically?
So you should either accept user id as a parameter or you should let the JWT authenticator take care of it.
Example REST API call would be
GET /user/data?userId=1234

REST api - How should the client supply userid to the request URL for its user resource?

A client needs to login with a username/password the first time. A JWT token is returned for future requests. The token will have a userid so that the server can fetch the user's resource from the database.
The problem I have is the client needs to form the request URL to update its resource let's say POST /users/{userid}. How should I get the userid for the client? I can't access the JWT token which is stored in a httpOnly secure cookie. Should I store the userid on the client somehow? So that it can use it for the URL?
I see your problem now. You are afraid of losing some of the advantages of a RESTFUL api, a unique resource locator,
I often have a set of URIs that start with the path that indicates that operations are on the currently authenticated user.
/current/profile
/current/blog_posts
In such cases I pull the user out of the request context on the server, which I can get by parsing the JWT token.
And when I want to operate on other users I use the identifier instead
/{{user_id}}/profile
/{{user_id}}/blog_posts
I'm not sure whether this is strictly RESTFUL, but it does give users of my API a stable and discoverable URI. I've used this pattern with a number of projects and teams without complaint.
If you really must get a user identifier two ideas idea comes to mind:
Return the user_id along with the jwt token.
Make an extra API call
to get the user_id from the server and then use that for all
subsequent calls.
Oh, another option comes to mind. Change your notion of a user_id and use the username (which you already have) instead.