Cookie based authentication with Spring Security | Spring Boot Backend #3.2

preview_player
Показать описание
In this video I will show the cookie based authentication with Spring Security. I will authenticate a stateless application with the cookies. And I will show the differences with the JWT authentication.

Content of the video:
* the HTTP filters. One will be dedicated to the regular authentication with the username and password, and the other will be dedicated to the cookie based authentication;
* the configuration of Spring Security. I will show how to add multiple HTTP filters, the exception handling with an Entry Point, the session management in a STATELESS mode and the path which need authentication and the one which don't;
* the creation of a token to be used in the cookie.
* The injection in the SecurityContext of the Authentication Bean for the usage in the controllers of the annotation @AuthenticationPrincipal.

Icons:
* Browser by Nawicon from the Noun Project;
* file document by Phumpsky from the Noun Project;
* Lock by tezar tantular from the Noun Project;
* Share by Sujono sujono from the Noun Project;
* User by ✦ Shmidt Sergey ✦ from the Noun Project.
Рекомендации по теме
Комментарии
Автор

I've searched all day for docs, tutorials - anything - that explains how to configure Spring Security for authentication NOT through Spring Security's built-in form. This is the only tutorial I've found that actually gets to the point of what an actual auth workflow would look like. Thank you!

fasolplanetarium
Автор

love the interlude explanations in the middle of the video like in 1:45 very helpful

livb
Автор

Muchas gracias, Sergio.
Eres un gran maestro, se agradece canales como el tuyo que ayudan a los demás a aprender.
Un saludo, like y new sub!

alvaritodark
Автор

When I send the request in the curl I always get UserDto == null, I switched your code to spring boot security 6 and java 21, spring boot 3.2

hardsystem
Автор

I am sooo confused I am a beginner. Is it possible to integrate this approach into view based authorization? By that I mean using MVC controller, and not REST. If yes, then what should I do? I use mechanism with the userDetailsService and this classical form with login and password.

revel
Автор

Context: I have implemented Google OAuth2 login at gateway and once google login is success, I will store the user details if not exists in db and create a jwt token with roles/permissions based on type of user logged in. There are couple of downstream microservices are behind the gateway (not necessarily in same cluster or in same tenant or same cloud provide). Once login success, the gateway will respond with generated jwt token to browser which can be used for all downstream microservices later. This is initial requirement and later we got a requirement to maintain only one user login session per user account. As we already made it as stateless, for server there is no way for us to determine no. of logged in sessions. So we introduced session manager which stores these jwt tokens at Gateway and maintain the recently login session, remaining can be invalidated (now it's stateful at gateway + stateless for downstream microservices (all downstream apps are capable of self verify the jwt tokens by secret key). It is working fine but we ran into other problem.

Problem: Because of our session manager requirement, the user cannot work on multiple browser tabs of the same site because it will ask for login. If he try to login, the other tabs will be logged out due to 401 error because the server thinks other tabs as separate login sessions.
I know we can make it work storing that jwt token inside a cookie, which can be used across the tabs but is there any other way to solve this problem? Or we used implement a complete stateful security (at server side) with common session storage (redis) and provide access to all downstream services? The reason we haven't choose this approach is all downstream services can be anywhere and for each request, it has to fetch the session from redis, which introduce the network latency

What is your thoughts/suggestions on this?

rajivkumar-ubuj
Автор

So I can make a call (POST request) to programmatically authenticate and get those cookies. Then, I can set those cookies via javascript code in the user's browser. And then, if I have a frontend app (i.e., AngularJS), and it is configured to rely on those cookies, then I'll not get any login page when loading this AngularJS app, right? Since AngularJS uses the cookies that we got from the POST request, right? I have an external app (that will load my app in the iframe), so the external app will authenticate to my backend (via POST), set those cookies in the user's browser, and then will call my app in the iframe. And my AngularJS app should load without the login page. Do I understand it correctly?

VladVlad-cytn
Автор

One more question: isn't this solution vulnerable to CSRF? Yes, we don't have sessions. But imagine a button on other site with delete request to protected url on ours. User clicks it and authentication cookie will work on our site. Or I am wrong?

ram
Автор

Thanks, it was really interesting but there's something I don't understand : how is Spring supposed to know it needs to use your "UserAuthenticationProvider" class ? In the config class, are you not supposed also to override builder) method to specify how the authentication will execute ?

Anthony-zcff
Автор

Hi! Thank you so much for your videos! However, I encountered an issue with authentication when I accessed the "/sign In" endpoint. The @AuthenticationPrincipal did not work, and the user argument was null until I injected a provider into filters and called provider.authenticate() to put the user into the security context.

DanilaTrapeznikov
Автор

i very curious about your experience, how long have you study spring framwork?

nguyenhoanganhk
Автор

This tutorial is not working anymore. It is deprecated. Just a head up for new watchers like me

tylerdurden
Автор

Thanks for sharing this video, I'm thinking of the scenario where the cookie is HTTP only so no JS code can access, but the JWT token inside the cookie contains the user Roles and Groups that the client side JS uses to show/hide pages and UI components (example hide the button create when not admin). What can we do in this case, do we have to create a new endpoint that uses the cookie and returns user's habilitations ?

marouaniAymen
Автор

Hola!

First of all thanks for this video, it was really useful for implementinng my own authentication. However, a few questions raise, like how to make remote session invalidation possible.

Say my token is stolen by someone, and I want to prevent them from using it. I'd go into an endpoint and say "invalidate all my sessions" but how could I do this in the server? The token is one per user, no matter where they log in from.
Maybe include as part of the cookie a "loggedInAt" key with the current millisecond and persist that in database, along with extra identifying data like IP, device identifiers... and a false "expired" key which I set to true if the user decides so?

What are your thoughts on this?

arielcg_
Автор

This code is not working. Where is authentication provider injected because i am getting null pointer exception as it is not going in the authenticate method as well as it is going to create the cookie even if wrong password is entered.Could you please reply quickly by checking your code.

PraveenSingh-szzj
Автор

Hi Sergio. First of all, many gratitude for such a well done content. I have almost watched the whole videos available on your channel.

I'm currently facing something very weird with Authentication (I took example on this particular video), and I would like to know if you can help me: My issue is that unauthorized HTTP call is going through the filters and unexpectedly the HTTP Client receives 200 with empty content where I expected 401. Any idea what could have been done wrong on my side?

arnaudpoutieu
Автор

Hey, first of all, thank you for the great tutorial. I have a problem with cookies in my application at the moment. Whenever the user authenticates themselves and logs into the application and gets the cookie, they can then access the end-point again to login, and get a new cookie. Is there a way to prevent the user from login in again, once he is logged in? Basically, so they cannot do concurrent logins and 'spam' the end-point constantly.

itsdaitonxd
Автор

Hey, why do we need to clear the security context in logout? Won't it be cleared anyway when the request is completed?

Areeb
Автор

Can I just put jwt token in the cookie?

ram
Автор

Hi I pulld code from repository in description TAG chapter_3_2 and it's not working for me. Authetntication provider is not called at all.
I am getting error:
Full authentication is required to access this resource
at
at
at
at
at
at

petarmikulic