No video
Google OAuth Login Application Using Java Spring Boot and ReactJS in Less Than 15 Minutes
By the end of this video you will know how to setup Google OAuth login for an application and a general idea of the source code used to create this Spring Boot with React App.
Setting up Gmail Login
console.cloud....
Source Code:
github.com/The...
Docker, MongoDB, and Java Spring Data Quick Start
• Docker, MongoDB, and J...
Quickstart Docker, PostgreSQL, and DBeaver:
• Docker, PostgreSQL, an...
MongoDB Docker Image:
hub.docker.com...
Spring Data MongoDB Documentation:
docs.spring.io...
Docker Installation
www.docker.com...
Windows Installation and Hyper-V (Virtualization) Details
docs.docker.co...
#react #java #oauth
Пікірлер: 100
There's actually an incredible amount of information to digest here. Pretty sure most the courses that build this sort of application are 3+ hours long. I would pay to watch you build this application from scratch and talk about every line of code. As I learn Spring Boot, one of the biggest things I don't understand when looking at other people's projects is what lines of code were required per some documentation, and what lines of code were written by the developer to implement a feature from scratch. I feel very overwhelmed and all I'm trying to do is provide an OAuth2 login to my back-end and start gaining access to user data on front-end react site. You've done a whole lot of that process in this video, but I'd rather not just copy/paste code...I need to understand what I'm looking at.
@TechTutorRyan
2 жыл бұрын
For now I am planning to make shorter videos to try to reach 1000 subs first. After I reach that, I plan to revisit these types of videos as they take me a lot longer to plan, create, and edit.
@tejap463
2 жыл бұрын
@@TechTutorRyan You will get subscribers if they like your content. You have knowledge you have done react spring boot oauth2 login. But you did not explain it. As Matt said if you would have explained the end to end flow this video might have got 100k views and your subscribers would have grown beyond 1000. So start putting the good content and your views and followers grow automatically. You are thinking is other way around.
@sigmawolf228
2 жыл бұрын
@@TechTutorRyan well 7 months left have you reached 1000 subs? It's not about subs, it's about loving the thing you do...
Man, thank you, I was feeling so bad, cuz I couldn't understand how connect the both sides, and I was watching a lot of videos too long, and I felt so frustrated, however with this video you help me a lot, thank you a lot dude, cheers From Chile (South america)
@TechTutorRyan
2 жыл бұрын
You're very welcome!
@ignaciobriones3769
2 жыл бұрын
@@TechTutorRyan hey man, I was trying to run the app, but I have a problems with the database I mean, how can set up the database, if u can say me, thx again pal!!!
@TechTutorRyan
2 жыл бұрын
@Ignacio Briones are you running it locally and having issues or running it on Heroku. In the video I show how you can setup a database for Heroku using a free tier from a site: kzread.info/dash/bejne/qpt107dydLm5eKw.html
In case you just have arrived here as spring boot oauth2 docs say, the redirect uri has changed to /login/oauth2/code/{your provider here} in this case the redirect uri is /login/oauth2/code/google
@pratiksavla
2 жыл бұрын
hey how did you solve this? I tried the url you mentioned but it still doesn't work
Perfectly worked. Thanks
thank you for the video. i'm currently also build a reactjs and spring boot app for authen, but still stuck on oauth2 google sign in (CORS issue when backend redirect google sign in to frontend). Gonna take time to read your code.
@TechTutorRyan
3 жыл бұрын
Sounds good. Let me know if you have any questions.
Why do you have a full setup spring boot project, after 5 minutes without showing what you added or did there... (" in Less Than 15 Minutes" - you basically did everything before you started the "tutorial"...)
Hi Ryan. I would like to thank you for your video and project template. With a bit of debugging and reading other sites explaining spring security oauth2 flow I was able to implement my own Oauth2 stateless login using my company oauth2 provider. I spent about 5 days learning and testing but it all went well! Maybe next time you can try going through each step of the oauth login flow debugging so we can have a better understanding of what it's going on. Regards.
Nice. I will try this, but I know I need to tweak this as I am embedding react inside boot
Thank you so much
Good one. Thanks!
@TechTutorRyan
3 жыл бұрын
You're welcome!
Thanks for video just if fonts was bigger then it was good to follow on mobile as well.
@TechTutorRyan
3 жыл бұрын
Thanks for the feedback. I will try to zoom in a bit more in future videos.
Hi, I ran your code using my own Google API account, but the URIs is exactly the same. However, after I logged in with a Google account, it did not redirect back to the page, and caused a "Timed out after 30000 ms ..." alert. Can you kindly check your code if it is still working? Many thanks!
How do i hit an API from react application? Its giving me 302 found error. Something related to redirect URL.
Thanks a lot! This looks like what I've been really trying to implement for my portfolio project s so I can start applying soon.. I have 1 doubt if you have time: 1. How on earth does sending an HTTP request to the "GOOGLE_AUTH_URL" (which is actually context root of Spring backend / login URL of Gmail's OAuth2 Authorization server) become a URL that is accessible via the frontend? In other words, the redirection by default happens on the Spring Boot backend, I don't see how the redirection done via the Oauth2 Client dependency on backend directs the frontend React app to said URL, because the front and backend apps are different applications possibly under different domains even, so a redirect on the backend is not visible to the frontend? 2. Similarly, for the "redirect_uri", I have pretty much the same confusion. The redirect happens on the Spring Boot backend but yet the frontend React app is different application
@TechTutorRyan
2 жыл бұрын
I will try to rewatch the video when I get a chance to remember exactly what was happening in this video. In the mean time, it may make a lot more sense if you watch the video I recently created, which is doing something very similar but with a lot less code. kzread.info/dash/bejne/p5uTmpuAqJO1p5s.html
@bluex217
2 жыл бұрын
@@TechTutorRyan Thanks very much! I almost have this working I think and just 1 more confusion I think. I'm really confused about all the "redirect uri's" In google project, I've configured 2 redirect_uri's like below: 1.localhost:8080/login/oauth2/code/google (this is for Spring Boot app with oauth2 client dependency) 2. localhost:3000/oauth2/redirect (this is a route on React frontend app where I'd like user to be redirected after successful authentication with google login form) Therefore, I have a "login with google" anchor tag in my frontend app, which, when clicked, follows the URL in your code like so to: localhost:8080/login/oauth2/code/google?redirect_uri=localhost:3000/oauth2/redirect When I click this button, not much works as expected. I'm redirected to an error page for my backend at at "localhost:8080/login?error", and there is option on page to login with google, when I click that and login successfully , it does not use the "redirect_uri" specified in query params of the url in anchor tag to redirect to my frontend app at "/oauth2/redirect", it just redirects to the context root of my spring boot backend at "localhost:8080" The concept of the redirect URI is boggling to me because google says for redirect URI that "Users will be redirected to this path after they have authenticated with Google." But in fact this is not the case, because 1 of the URI's we add "/login/oauth2/code/google" is not where the authenticated user is redirected but rather that seems to be where we need to go in order to reach google login form to authenticate in the 1st place. For example in your frontend code, when you click "login with google" anchor tag you send user to "localhost:8080/login/oauth2/code/google?redirect_uri=localhost:3000/oauth2/redirect" So both the URL which leads to the backend on 8080 AND the url query parameter "redirect_uri" are both set as redirect URI's in the google project. In what context is either of them a "redirect uri" ?
@TechTutorRyan
2 жыл бұрын
@@bluex217 Since this was an older version of Spring, I will try to explain it from what I remember. As I mentioned, I think it has become a bit simpler in newer versions such as the latest video that I created. From what I recall a lot of the configuration and URL pathing for Spring is handled starting in setting the redirect URL in the application.yml. Here is where I found example for that: docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html#oauth2login-advanced-redirection-endpoint Next there was a lot of trial and error in the SecurityConfig.java class in order to set up the custom authentication, but I am sure that the Spring documentation will have a much simpler example now that it is a year later. You will see I had added a customOAuth2UserService in that SecurityConfig file. More details on that here: docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html#oauth2login-advanced-oauth2-user-service In general though, what is happening is that your Java code will be creating APIs for Google to hit during a redirect. Some of this can be confusing because Java Spring does a lot for you behind the scenes. Through various configuration options though, your Java Spring code can perform that second redirect to another URL that your front end code has an API setup for. Let me know if this makes things any more clear or if I just made it more confusing. 😅
@bluex217
2 жыл бұрын
@@TechTutorRyan Thanks a lot my friend:) I understand most of what you described, but still no luck unfortunately. I'll explain my experience/issue below: 1. If I specify the redirectUri in the Spring config file, it works to log in, but redirects ALL requests to all controller mapping in the application. This means if I set up an endpoint to return the openId data, an axios request (for example) to that restcontroller is also just redirected to my frontendapp, without the data needed by the frontend being present within the HttpResponse 2. To rectify issue in no. 1 above ^, I removed the redirectUri from Spring config file and instead implemented a "SimpleUrlAuthenticationSuccessHandler" which calls "getRedirectStrategy().sendRedirect(request, response, "frontend-endpoint-goes-here"); With this approach, logging in is successful, and even hitting the endpoint which returns google openId info via localhost browser works. But unfortunately, this presents a CORS issue now whenever I try to send the request from another origin (such as localhost:3000 for my React app) I have tried everything I could find online but it appears that whenever I hit any endpoint without the "redirectUri" configuartion property I get a 302 indicating that thet spring app redirected and the frontend app was basically left behind. So without redirectUri config property, CORS failure. With redirectUri config property, everything is redirected rendering my rest controller useless, because I can't return anything I need to , to a client
@TechTutorRyan
2 жыл бұрын
@@bluex217 If I understood correctly, it sounded like you are saying that all requests were being redirected even after you authenticated? If that is the case, are you sure your HttpSecurity is configured properly? It should know if you already authenticated or not and only when your token does not exists or expires should it redirect to the Google Auth.
I've created this exactly as in the github, and configured the uri urls in google, but for some reason I get unauthorized redirect uri error , any idea why this might be?
Thank you. How can we use API server for mobile apps? In-app webview is not working
Maybe I'm too late to the party but I'm trying to implement this exact thing but I just don't understand how to validade the authentication from the frontend. I already have a spring boot app with jwt authentication. oauth2 implementation would be simple if I wanted to use the spring boot app as frontend, which is not the case. I want to have a react server just like your example. I managed to implement most of the things but now when I login with oauth2, right after logging, it redirects me to the localhost:3000/oauth2/redirect as expected but there is no token? I'm confused, is oauth2 suposed to generate a jwt?
Hi, may I ask in the application.yml, where do you store the value of {baseUrl} and {registrationId}? why don't you need a dollar sign in front like "${variableHere}" ? Thank you for this great tutorial.
@TechTutorRyan
3 жыл бұрын
The dollar sign is more common in Java Spring, but you will see in YAML where only the curly braces are used. Sample from Spring Documentation: docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2login-sample-redirect-uri
You have a video that shows a SSO springboot react front end and postgress db and how to deploy the app from github
Hi, is there a method where a JWT token would be able to call for a CSRF token within Java? Or would just JWT authentication be sufficient?
@TechTutorRyan
3 жыл бұрын
From my understanding, typically you do not need both JWT and CSRF. In my project I actually disabled CSRF in SecurityConfig.java. For more information about CSRF configuration for Spring, you can also take a look here: docs.spring.io/spring-security/site/docs/current/reference/html5/#csrf
Thanks for your video.Can I use this tutorial to do the same with Facebook,Github,... login?
@TechTutorRyan
3 жыл бұрын
Yes it will be very similar for other types of login. Here is a reference to the Spring blog in 2018 where they mentioned integration with Facebook and Github. I am sure there are more features by now though: spring.io/blog/2018/03/06/using-spring-security-5-to-integrate-with-oauth-2-secured-services-such-as-facebook-and-github
@xuaniennguyen6573
3 жыл бұрын
@@TechTutorRyan Thank you so much for the help.
@TechTutorRyan
3 жыл бұрын
@@xuaniennguyen6573 no problem!
Just curious, what is the typical redirect uri, and is it universal to all oauth2 services?
Honestly I'm not sure why you're generating the jwt tokens by youself, shouldn't this be taken care by the Authorization server?
Hi, I have the setup the spring security in backend. Please help me to get enable the same call from react app setup. and I don't want any login button. Needed, on reload api authentication should happened and back with the output.
@TechTutorRyan
2 жыл бұрын
I am not sure I understand what you mean. When you use Google to login, it will require you to use the Google login ux, because it directs there first add then after a successful login it will redirect to your app with a session.
Good job. I'm trying to remove the sign in page provided by Google because I keep getting 302 redirection status when I send requests. Any suggestions, thank you
@TechTutorRyan
3 жыл бұрын
I don't think you can remove the redirect to Google Sign In, because Google is handling the login credential validation. Do you currently have this deployed on a server or is this running locally?
@hajaressaidi7021
3 жыл бұрын
@@TechTutorRyan just locally. What I'm trying to do is to send requests from my react app to my spring boot api, so I'm going to send the token from front and so, I can use restricted paths, but unfortunately I get the 302 redirection
@TechTutorRyan
3 жыл бұрын
Are you able to share some of the code you are trying to use? The sample code I posted for this video on my Github already sends a Bearer token from the client to the Java server without any issues. I am curious to see what may be causing your code to force a 302 redirect.
@hajaressaidi7021
3 жыл бұрын
@@TechTutorRyan link to my issue stackoverflow.com/questions/67247780/302-redirection-oauth2-authentication-spring-security
@TechTutorRyan
3 жыл бұрын
From the code I can see I am guessing that you are not redirecting the user login to your Spring Boot server and instead you validated the user to get a token a different way. If you are using spring-boot-starter-oauth2-client in your pom it is expecting the user to go through the flow kicked off by the client to the server so it can create a session for the user. I think it may be easier for you to fork the code that I provided and then build off of it from there.
Can I use MySQL instead of MongoDB? if I can, then what do i have to change? Thank you.
@TechTutorRyan
3 жыл бұрын
Yes, you can use MySQL as well. There will be some differences in how you use Spring Data, but it should be pretty similar to my video about PostgreSQL. Here is the link to that video: kzread.info/dash/bejne/foqo2Kipe6iydKg.html If you have any other questions, just let me know.
@hieupham8791
3 жыл бұрын
@@TechTutorRyan where do we get the tokenSecret: 926D96C90030DD58429D2751AC1BDBBC from? or is it just a constant to generate a token?
@TechTutorRyan
3 жыл бұрын
@@hieupham8791 Correct. This is just a value that you will want to create on your own and keep secret. This value is used to sign the JWT token. Take a look at the TokenProvider.java file to see where it is being used.
@hieupham8791
3 жыл бұрын
@@TechTutorRyan Thank you
@TechTutorRyan
3 жыл бұрын
@@hieupham8791 No problem! Let me know if you have any other questions.
Hello you paste url in google console localhost but i want live server URL also i put thier live url but this is not working
@TechTutorRyan
3 жыл бұрын
This video was helping you to get setup and run it locally. Check out this video for deploying a live server. kzread.info/dash/bejne/qpt107dydLm5eKw.html
Hello, this video describes exactly what I need, but I am struggling with the newer version of springboot(2.6.7 atm) and spring cloud gateway. Gateway serves as an entrypoint to all apis. React app is supposed to access those apis. I use keycloak as IDP. As far as I understand, when we set up .oauth2Client() in spring security, it enables some endpoints to enable oauth2 flows. But I can't find what are they. Actuator doesn't see them as well. I would like to implement either auth code grant on FE, with token exchange on GW. Or even better a complete BFF pattern, where gateway will handle oauth2 itself, and will establish cookie session with react. Any help would be appreciated....
@ogyct
2 жыл бұрын
Actually I see already. You made some magic with that redirect_uri. I don't think, this exists by default, right? A deeper dive in would be helpful.
@hugofernandez2344
Жыл бұрын
Is there any example with React, Keyclock, a set of social identity providers and spring boot? I'm struggling to find any example, I found one which is using @react-keycloak/web but is not working not sure if it's the node version Im using
Hi. I keep getting this error: "com.spring.login.exception.BadRequestException: Sorry! We've got an Unauthorized Redirect URI and can't proceed with the authentication" when I try to log in. Where do I get the registration ID from? I've also tried to replace the {base url} with the actual base URL value and the registration id with the client ID. All I get is "Error 400: redirect_uri_mismatch". Please help.
@french7948
2 жыл бұрын
Never mind. I found a way around it. Thanks.
@priyankakondapaneni8306
2 жыл бұрын
same error.How did you solve?
I'm confused for the same reasons as Bluex217. Can you elaborate about the "tokenSecret" property you have in your code? Where does it come from?
@bluex217
2 жыл бұрын
Hey my friend! While there are a few aspects to particularly the backend application which MAY be a good idea to implement depending on use case, I've finally gotten the main premise of this to work. (Long comment, but this was confusing as shit to me initially, so can't hurt :) ) Do the below: This assumes you have a frontend Node.JS application running locally on port 3000. This also assumed that within your frontend react app, you have created a component for route endpoint "oauth2/redirect" (just make sure this route matches the redirect URI in point number 2 below. This also assumes you have a backend spring boot application running locally on port 8080 In google.developer.com, where you create a google project, add both of the below redirect URI's: 1. localhost:8080/login/oauth2/code/google 2. localhost:3000/oauth2/redirect (again make sure you have a route open with this endpoint in frontend React app) In your backend spring boot app, in application.properties (or yml), add the same redirect URI you placed in google proj. in previous step, which has URL to the frontend app - This would be "localhost:3000/oauth2/redirect" THIS PIECE WAS MOST IMPORTANT FOR ME AND SEEMINGLY NOT DONE IN THE UPLOADER'S PROJECT: In your frontend app, for the button/anchor tag which says "login with google", have the href redirect to your backend app context root / login/google so "localhost:8080/login/google" and THIS will have your frontend app redirected to the Google login form when you click the button. Once you log in successfully, provided your 2nd redirect URI configured in google project matches the redirect URI in your spring project's properties file (mentioned above) it will redirect to your frontend app successfully. The only issue here is that, once you are redirected to your frontend app after logging in with google, the user's details do not seem to be anywhere in the HTTP response. For this: 1. Create a controller mapping in Spring Boot project which autowires the Oauth token like this: @GetMapping public Map getCurrentUserDetails(OAuth2AuthenticationToken oauth2AuthenticationToken) { return oauth2AuthenticationToken.getPrincipal().getAttributes(); } 2. Now that you have the above-mentioned endpoint which returns user's google details, have the page on frontend app where you're initially redirected to immediately make an HTTP Get request to the above endpoint in backend, and then it can retrieve the user's info, IF logged in ,, of course
@samueltb2182
2 жыл бұрын
@@bluex217 I've found this other video helpful kzread.info/dash/bejne/iIqim7GAadHMeJM.html
Thank you very much for sample. After some fix related to @Autowire, it is working for authentication part. I could do authentication successfully and redirected correctly to redirect URL with token. Whe i am using /profile API to get currently loged-on user ( I am trying to connect from an Angular App running on port 4200) getting some 'cors' issue though the correct settings for cors is given. I am not sure abt the issue. Have you seen anything like this?
@TechTutorRyan
3 жыл бұрын
Any CORS setup should have been handled by the SecurityConfig and WebMvcConfig classes. Also you shouldn't need to use @Autowire if you are using Lombok and @RequiredArgsConstructor from my example. After adding RequiredArgsConstructor, your imports will automatically wire in just be initializing them as 'final' like they are in my sample project. Details on this can be found here: projectlombok.org/features/constructor
Hi, I have read through your source code. I have a question, how does the HttpCookieOAuth2AuthorizationRequestRepository class work and what does it do in your application?
@TechTutorRyan
3 жыл бұрын
Hello, That class is storing the authorization request for 180 seconds as a cookie. This basically prevents the need to keep performing the OAuth validation for each incoming request until the cookie expires. You can see where it is added into the HttpSecurity configuration in SecurityConfig.java: authorizationRequestRepository(cookieAuthorizationRequestRepository())
@iennguyenxuan3577
3 жыл бұрын
@@TechTutorRyan Thanks for answering. But I have a couple of unknowns: Does this class act like a filter? When is this class called?
@TechTutorRyan
3 жыл бұрын
@@iennguyenxuan3577 correct this is a filter class that is added in that same SecurityConfig.java file: // Add our custom Token based authentication filter http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
@iennguyenxuan3577
3 жыл бұрын
@@TechTutorRyan Really sorry,I am newbie with SpringBoot and Spring Security. I still don't understand what you mean. TokenAuthenticationFilter() and cookieAuthorizationRequestRepository() are the same?How does each one work ?
@TechTutorRyan
3 жыл бұрын
@@iennguyenxuan3577 TokenAuthenticationFilter is a custom class I had created to validate the JWT token as well as load the user from the token. The cookieAuthorizationRequestRepository is used to tell Spring that the OAuth flow has already been completed and the result is stored in the cookie.
I did the same method but i am not getting custom login page
@TechTutorRyan
3 жыл бұрын
What exactly do you mean by custom login page? This app utilizes a redirect which takes you to a Google login page. In my opinion this is the better approach because you are not storing any credentials on your end and letting Google handle the authentication of the user credentials.
@someshananthan9764
3 жыл бұрын
@@TechTutorRyan in my project we are using spring boot as backend and react as front end. In your application when i run localhost:8080 i am getting page with loginwithgoogle button. But in my application it goes to default login page that contain google hyper link. This one is default page in spring boot. How are you redirecting it to custom created page?? When hitting localhost/login
@TechTutorRyan
3 жыл бұрын
@@someshananthan9764 If you mean how do I tell Spring Boot to redirect to my React App, it is in the application-local.yml app: tokenSecret: yourCustomSecret tokenExpirationMsec: 864000000 authorizedRedirectUris: - localhost:3000/oauth2/redirect Don't forget to take a look at this class as well: OAuth2AuthenticationSuccessHandler.java
@carloseduardosalvador8295
Жыл бұрын
@@TechTutorRyan Where you get that token secret??
@TechTutorRyan
Жыл бұрын
@@carloseduardosalvador8295 it is generated in the Google API console. It may be easier to follow my newer video that shows a bit of a simpler setup with newer code and just backend code. kzread.info/dash/bejne/p5uTmpuAqJO1p5s.html
canyou continue this video by validating jwt token with custom login
@TechTutorRyan
3 жыл бұрын
What exactly do you mean by custom login? Do you mean instead of using Google, you want to store the username and password in your own database?
@shanmukhavarma3361
3 жыл бұрын
@@TechTutorRyan custom login means form based login
@shanmukhavarma3361
3 жыл бұрын
My case is we must have Google sign in option followed with form base login like User manually enter username and password if username and password is valid we have to generate the jwt token. Same for google sign in if login successfully generate jwt token. This both features should be implemented in the single applications.
@shanmukhavarma3361
3 жыл бұрын
This can be done on server side or we have do google sign in on frontend side and we have to pass access token to server to generate jwt token? By the way I am comfortable with any front end technology.but upload video on Doubt
@TechTutorRyan
3 жыл бұрын
@shanmukha varma in the client code OAuth2RedirectHandler.js is actually storing a token that is used with the backend code. This token will be valid until the token expires, which is set on the java side via the tokenExpirationMsec variable. Additionally, APIUtil.js will use that token for its requests to the server. On the server side take a look at TokenProvider.java to see how that token is validated. The only main difference between using Google and creating your own custom login, is that when you use Google your user will be sending their login information to Google so that it can validate it. If you wanted to store your own user login information, you would want to encrypt it in your database and then update SecurityConfig.java to handle that authentication.
Can you share the project ?
@TechTutorRyan
3 жыл бұрын
It is in the description of the video, but here it is again for convenience. Source Code: github.com/The-Tech-Tutor/spring-react-login
your code is way too complex
Thank you. How can we use API server for mobile apps? In-app webview is not working
@TechTutorRyan
2 жыл бұрын
I assume you didn't use React Native for your app. What language is your app built with?
@mdmahmudhasan1680
2 жыл бұрын
@@TechTutorRyan It's flutter.
@mdmahmudhasan1680
2 жыл бұрын
@@TechTutorRyan It's flutter.
@TechTutorRyan
2 жыл бұрын
@@mdmahmudhasan1680 I see. I would suggest using a flutter package to handle the login, whereas I was using a Node library. pub.dev/packages/google_sign_in
@mdmahmudhasan1680
2 жыл бұрын
@@TechTutorRyan Thank you I was able to use this but the token I am receiving here is giving unauthorized in spring. Give me some suggestion please