We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Misha Infotech • 2 years ago

Hello bro Thanks a lot for your support.

I am requesting u to please provide sign in apple also I am using your social media login but stuck on Apple Oauth2 Please help. Thanks U for advance

xenogew • 4 years ago

Hello Rajeev
Thanks for your article and example.
I would like to ask, if the case I want to implement with Twitter login, how to approach?

chanakya sunkarapally • 4 years ago

Hi, Is there anyway to send the token to the client in the Authorization header instead of the queryString? Thanks

swaprks • 5 years ago

https://uploads.disquscdn.c...
When i am redirected to "/oauth2/callback/google", i am getting 403 forbidden error. I have attached the screenshot. Any idea what can be the reason?

Marcin Nowak • 5 years ago

Dear Rajeev, Thank you for the outstanding tutorial which let me learnt a lot.
One thing worth to mention is that deserialization with Java implemented in CookieUtils is very insecure. The attack vector can be with specially prepared content of the cookie containing serialized Thread/File or other classes to exploit the system.
I would suggest using signed and encrypted JWT as the content of a cookie instead.
Appreciate your knowledge sharing!

Alexander vT • 5 years ago

Yes this is really severe. The attack can change the url that direct the backend to google to his own and therefore claiming a user that he does not control. I would suggest you fix that or at least warn the reader...

Agus Cardeilhac • 5 years ago

Hi CalliCoder !. Really amazing tutorial !. This is what I was looking... There is another tutorial done by Wojciech Lesniak in pluralsight, which is outstanding... Wnated to know the following: How could I have together 3 types of authenticated principals ?. I mean maybe 2... I have the one that comes from Form Login and the others that come from Oauth (maybe Facebook or Google, etc). Because I was looking a common interface or something alike...

Soumitra Roy • 5 years ago

Getting error "java.lang.IllegalArgumentException: Illegal base64 character 2f" if I put query param for redirect_uri=/auth?cId=abcd

Can you please let me know what to do for this?

No Name • 5 years ago

@Override
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) {
System.out.println("removeAuthorizationRequest");
return this.loadAuthorizationRequest(request);
}
it just loads the OAuth2AuthorizationRequest, where is the remove part?

Saman Kh.R. • 5 years ago

How to mock CurrentUser in a MockMvc test ?
thx

Abinandhan • 5 years ago

Hi thanks for the detailed tutorial, I would like to how do you build such complex application, what should I do to improve the same, is reading documentation the only way, I would like to understand your though process involved in building like what beans to configure/ how to configure etc.. for example HttpCookieOAuth2AuthorizationRequestRepository

marwen hanzouli • 5 years ago

Hello sir, thank you very much for this tutorial, i only understand the mechanism of Spring Security with your tutorials, like this.. I copied your code in my project and it's runned successfully , but when i want to build my JAR file with mvn clean package command i got always this error .. i need the JAR to deploy https://uploads.disquscdn.c...

Rachid Amghari • 5 years ago

Good idea to avoid using cookies to open your implementation to be used also by mobile apps.
But I don't think it's safe to put the token in query param. Yes the query param is encrypted with SSL, but your browser history saves this visited url and it could be used by another person who has access to your machine.

IMHO, As a workaround, I think we need to implement 'Code Authorization Flow' also in front end side, so when the user is authorized by backEnd server , it receives one time code to exchange it by a valid token in a proper and secure way.

Prasanna • 5 years ago

nice tutorial but it good if you given details to configure setting google,gmail,github.
I am getting issue with redirect URL mismatch

Rachid Amghari • 5 years ago

Google example:
Add this url http://localhost:8080/oauth2/callback/google to your 'Authorized redirect URIs' in google settings

Prasanna • 5 years ago

yes I done it thank you

AdiN • 5 years ago

I have that issue: java.lang.ClassCastException: org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser cannot be cast to .security.auth.model.UserPrincipal

Denis • 5 years ago

to solve this I've added OidcUser in declaration of UserPrincipal

public class UserPrincipal implements OAuth2User, OidcUser, UserDetails

Kaleemullah Nizamani • 6 years ago

So much code and I'm struggling how in testing this code. Where to even begin and what to test for such a long security setup. Can anyone please write unit tests with junit5 of this project. Or if anyone is interested in collaboration of writing unit test I'm available. Great effort.

Samuel Rego • 6 years ago

what is the url for refresh token ?? i tried with oauth/token its not working?

Alex Xxx • 6 years ago

"SecurityContextHolder.getContext().setAuthentication(authentication);" in AuthController, why do we need this code ? Its REST application, isnt it? So this code will authenticate our user in controller that is permitted for everybody, we dont have any secured service layer and client must put token to each request

Ioannis Lilimpakis • 6 years ago

Is it really safe to return the token as part of the URL? Is there another way to return it for the front-end client to acquire it?

Alex Xxx • 6 years ago

You can return it as you want, since you can control the handler, why it is less safe than other ?

Олег Павлюков • 6 years ago

The theme is very useful, but I can not learn this, because it is not repeatable. We write some class that has a lot dependencies which we going to write after 1 meter of the article and I need all the time explore imports of the class for be sure that it is just some custom class which we will write in a future or it is some class from spring security. Almost every class is red in IDE, it looks just awful and it is easy to make mistake and forget something or give a wrong class name, different then in code above. It will be awesome if you will write your articles in other order, how you write this code. But explains are perfect, thank you.

Nikolay Yakovlev • 6 years ago

For those for whom redirect is not working properly, just change in application.yml

redirectUriTemplate


to

redirectUri


it's in OAuth2ClientProperties class, Spring Boot 2.2.1

You may face it if

full authentication is required to access this resource spring boot

error occurs after redirection from provider (Google, Facebook, ...)

Ashish Kamble • 6 years ago

after changing that to `redirectUri`, now i cant goin forward after google login page,
with `redirectUriTemplate`, i can go foraward from google login page, but stucks at, http://localhost:8080/login/oauth2/code/google?state=G

Thomas Campbell • 6 years ago

I find it pretty amazing that it is this complex to just authenticate with a site. I'm only looking at this because Google is forcing this to be used by their APIs. This is far too complex

Oh but please don't think the thoroughness of the article isn't appreciate it. Very thorough.

Othmane Wahi • 6 years ago

very helpful, thank you so much. i tried to add authentification for linkdin, but LinkedIn OAuth2 access token api is returning only the access_token and expires_in values but not the token_type in the response. This results in the following error.

org.springframework.http.converter.HttpMessageNotReadableException: An error occurred reading the OAuth 2.0 Access Token Response: tokenType cannot be null; nested exception is java.lang.IllegalArgumentException: tokenType cannot be null

can you suggest a solution please !

umamahesh G. • 6 years ago

Hi
I use the code from your github. But I got error and can't find resolve of my problem:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'clientRegistrationRepository' in 'OAuth2ClientRegistrationRepositoryConfiguration' not loaded because OAuth2 Clients Configured Condition registered clients is not available
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' in your configuration.

Please help me on the same issue. I have my google clientId and clientSecret in application-dev.properties

umamahesh G. • 6 years ago

Hi
I use the code from your github. But I got error and can't find resolve of my problem:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'clientRegistrationRepository' in 'OAuth2ClientRegistrationRepositoryConfiguration' not loaded because OAuth2 Clients Configured Condition registered clients is not available
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' in your configuration.

Please help me on the same issue. I have my google clientId and clientSecret in application-dev.properties

Jose M Quijada • 6 years ago

Towards the top of this page, why do you say the following?

The redirect_uri is the URI to which the user will be redirected once the authentication with the OAuth2 provider is successful. This is different from the OAuth2 redirectUri.

Google official developer docs at https://developers.google.c... say the below about the "redirect_uri" parameter:

Required. Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in the API Console. If this value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch' error. Note that the http or https scheme, case, and trailing slash ('/') must all match.

In essence "redirect_uri" and "redirectUriTemplate" are one and of the same. This is Spring's documentation on "redirectUriTemplate" at https://docs.spring.io/spri...

redirectUriTemplate: The client’s registered redirect URI that the Authorization Server redirects the end-user’s user-agent to after the end-user has authenticated and authorized access to the client.

Mobile Web Specialist • 6 years ago

I think there are 2 redirects. The first one is the callback to the spring boot app after authentication with the provider; the second one is the redirection of your react/or any other single page application user to the required page after the spring app (the back end) gets the authentication response from the provider. That's why the first one starts with localhost:8080 and the second one with loalhost:3000. Hope that helps. But I am also having a problem with 'Full authentication is required to access this resource' error.

Rämán • 6 years ago

I am also having same problem. did you solve your problem

Mobile Web Specialist • 6 years ago

Hey, yeah I have solved it look at @Nikolay Yakovlev answer above. That is the solution.

Rämán • 6 years ago

Thank you it works

Parth Trivedi • 6 years ago

Very helpful, thank you....

Carlos Lazarin • 6 years ago

Thank you a lot for your tutorial!! Great job!

Diego Vinter • 6 years ago

First of all, congratulations and thanks for the tutorial. It's being really helpfull to me.
I just finished the second part. I could signup with e-mail, but i'm trying to login (using postman) and i'm getting the following error:

{
"timestamp": "2019-10-04T17:30:07.247+0000",
"status": 401,
"error": "Unauthorized",
"message": "Bad credentials",
"path": "/auth/login"
}

My request is:

{
"email":"my.email@gmail.com",
"password":"$2a$10$h5Nmga3DKljf2NGI3o3osermMDY7xtalqhUwfXezVWs9yVpvcFld"
}

I got the password from DB.

Can someone help me?

Thanks

Artur Nikitin • 5 years ago

this password is encoded you need to send the original password

Vaibhav hadole • 6 years ago

Great tutorial. It really helped.

Can you suggest hoe to implement logout for the same ? revoke token and also logout current user.
It would be very helpful.

Thanks in advance.

Himanshu Saini • 6 years ago

It would be amazing if you can update or suggest the solution to get this working after the recent facebook security upgrade. I guess it requires some of the changes in facebook app, but i could not find any working solution yet. Most of them are failing with redirect Uri and domain errors.

Alexander • 6 years ago

Hi
I use the code from your github. But I got error and can't find resolve of my problem:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' available

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'clientRegistrationRepository' in 'OAuth2ClientRegistrationRepositoryConfiguration' not loaded because OAuth2 Clients Configured Condition registered clients is not available
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' in your configuration.

Maybe someone has already resolved?

Nikolay Yakovlev • 6 years ago

Probably your parameters in application.yml is not under spring: prefix.
It should be:


spring:
security:
oauth2:
client:
registration:
google:
clientId: ...
clientSecret: ...

Andres Rodriguez • 6 years ago

Sir,
How can you add the RememberMe functionality in this project and integrate it with the TokenAuthenticationFilter. What would be the necessary steps in general terms to integrate the Remember me?

Thank you very much!

Ion • 6 years ago

Hey! How can I get the original fb token, in order to use it for future requests to fb after login?
In your solution you create an app token and the fb token is lost.

Przemyslaw Chlebus • 6 years ago

Is this flow compliant with native mobile clients ?

SednevMixail • 6 years ago

If someone install malicious app on phone and register the same schema "example://" he will get your token. Amazon and Google authentication services did it differently. They use native libraries as oauth clients and then pass id token to server.

Rajeev Singh • 6 years ago

Yes!

Imad Eddin • 6 years ago

Sir
This is one of the best tutorials/articles I have ever read about Spring security in general and social login.
I am trying to refactor a project using your code and build a parent maven project with separate service, dao, common and endpoints maven sub modules.
I would really like to share it with you when all done.
Thank you very much for your hard work. You are 100% the man.

Serhan Özbey • 6 years ago

Hi Rajeev,

Can you elaborate why you are disabling CSRF? Also storing access token at local storage is really not secure as far as I know and not advised. https://auth0.com/docs/secu...

As I know, the preferred way is httponly cookies with CSRF enabled.

Regards,
Serhan