The business scenario

Use Spring Security Oauth2 as the login scheme for the system

However, the login process and return results need to be specialized, for example:

  • Logs the last login event
  • Add user information to the returned content

After some thought, I decided to create a new login interface myself and call Oauth2’s ‘/oauth/token’ in it.

plan

Create the Oauth2 utility class

Create a utility class that calls its interface internally to log in, oAuth2Util.java:

@Component
public class Oauth2Util {

    /** * login **@paramUrl Login address *@paramClientId clientId *@paramClientSecret Client key *@paramUsername username *@param"Password," password *@returnLogin result */
    public static OAuth2AccessToken login(String url, String clientId, String clientSecret, String username, String password) {
        ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
        resourceDetails.setAccessTokenUri(url);
        resourceDetails.setClientId(clientId);
        resourceDetails.setClientSecret(clientSecret);
        resourceDetails.setUsername(username);
        resourceDetails.setPassword(password);
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
        restTemplate.setAccessTokenProvider(new ResourceOwnerPasswordAccessTokenProvider());
        returnrestTemplate.getAccessToken(); }}Copy the code

Create a new login method

LoginApiImpl.java:

@RestController
@Data
@AllArgsConstructor
public class LoginApiImpl implements LoginApi {

    // Address of the login interface
    private static final String OAUTH_URL = "http://localhost:9999/oauth/token"
    
    private final UserService userService;

    @Override
    public LoginResult login(User user) {
        // Request the login interface to obtain the token
        OAuth2AccessToken token = Oauth2Util.login(OAUTH_URL, "vue"."vue", user.getUsername(), user.getPassword());
        // Set and update the last login time
        user.setLastLoginTime(new Date());
        userService.update(user);
        returnLoginResult.builder().token(token).user(user).build(); }}Copy the code