K
K
ktyz19922020-12-16 21:30:53
Java
ktyz1992, 2020-12-16 21:30:53

How to check and save data about the principal (user) in the database at the time of authentication?

Hello! I am using Spring Security for OAuth2 authentication on a website. Authentication through Google and Github goes well - protected pages are shown, data about the principal can be extracted. However, it is required to store data about registered users in a local database. How to intercept the moment of authentication and if such a user is not found:
1. transfer to the site page with additional information about the user;
2. write a new user to the database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mark Struchkov, 2021-02-19
@upagge

I used for this
5tcpft-ss-tutxjp8emaoynfkda.png
There is a method

public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {

Authentication passes through this method. We kind of create a proxy for this class.
That is, first in this method we do
final OAuth2User oAuth2User = super.loadUser(userRequest);

Then we convert OAuth2User to the entity we need and save it to the database or update it. And we do any other necessary manipulations.
Next, we return
return new DefaultOAuth2User(appUserAllPermission, attributes, "id");

The only thing I do not know is how to transfer to another page in this case. I also want to note that we also have our own implementation of Oauth2, but the principle seems to be the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question