springsessione-commercecartshopping-cart

CartService and Authentication


I noticed that if you go to an online store, it allows you to view products and add them to the cart without authorization. I suppose I can achieve this, for example, by adding anyRequest().permitAll() in the configuration (I do not know if this is the right approach, I'm just learning programming). But then I don't quite understand how my shopping cart is saved after authorization?

I use Keycloak to get and validate tokens. I tried Authorization Code Flow and Client Credentials. But how can I link between userId and cartId.

At first I planned to insert the userId field into Cart, but there is no point in this field until I log in.. Then I remembered about the message broker, and for a second I thought that maybe Keycloak would send authorization messages by passing the userId, and Cart-Service would subscribe to the desired topic and fill in the userId field, but this is some nonsense, how will I understand which userId corresponds to which cartId.

Should I always use sessions (Spring Session maybe) here or..? I have heard that JWTs are an alternative to sessions, but they always require authorization, this is logical.

I have a mess in my head, I'm just gaining experience, please help me.


Solution

  • The cart state is in your front-end: in browser memory for Javascript based apps (Angular, React, Vue, etc.) or in server memory (session) for server side rendered application (Thymeleaf, JSP, etc.). It might also be saved in a cookie if cart state should be saved between sessions.

    This cart state is completely independent of the user authentication state.

    Once your user is authenticated (with client_credentials), you can get the user ID from the access & ID token claims and associate it with the cart ID.

    Subject is a good candidate for user ID, but you could also use e-mail or preferred_username when those are configured as unique and not null on your authorization server (Keycloak).

    JWTs are not an alternative to sessions. You can get rid of sessions on OAuth2 resource servers (being configured with JWT decoder or token introspection), but OAuth2 resource servers can be consumed only by OAuth2 clients and OAuth2 clients running on a server need sessions (session is used by clients, among other things, to store tokens between requests). As configuring Javascript based applications as OAuth2 public clients is now discouraged in favor of BFF pattern (middleware on the server configured as OAuth2 confidential client), you'll need sessions on this BFF to get OAuth2 working. Note that this session usage is not directly correlated with your cart: as explained above, cart state in session is an option only for server-side rendered applications.