M
M
Mark Ivanych2016-02-05 10:09:48
Spring
Mark Ivanych, 2016-02-05 10:09:48

Spring Security: how to authorize a user without a password?

Hello,
Help me understand how to make automatic login through oauth2.
I send a request to vk.com

String url = "https://api.vk.com/method/users.get"
            + "?uids={user_id}"
            + "&access_token={access_token}"
            + "&fields=uid,first_name,last_name,screen_name,sex,bdate,photo_100,photo_max_orig";
Map<String, List> result = getForObject(url, Map.class, userId, accessToken);

I get a response like this:
{uid=12345, first_name=xxx, last_name=xxx, sex=2, screen_name=xxx, bdate=1.5, photo_100=xxx, photo_max_orig=xxx}

As I understand it, authentication by uid should take place , but how is HZ implemented.
Accordingly, the vk_id field in the database exists.
I guessed to do so, but how much it is correct is not yet sure.
@Autowired
private UserService userService;
....
UserDetails userDetails = userService.loadUserByOauth2("vk", 12345);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));


public class UserService implements UserDetailsService {
    public UserDetails loadUserByOauth2(String provider, int clientId) throws UsernameNotFoundException {
          UserDomain userDomain = userMapper.getUserByOauth2(clientId);
          GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + userDomain.getRole());
          return new User(userDomain.getEmail(), userDomain.getPassword(), Arrays.asList(authority));
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question