lyh
3 天以前 2ab86210fb27787cb1be8976286b9b827f90997f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.lxzn.auth.config;
 
import com.lxzn.auth.security.UserJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;
 
import java.util.LinkedHashMap;
import java.util.Map;
 
@Component
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
    @Autowired
    private UserDetailsService userDetailsService;
 
    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        LinkedHashMap response = new LinkedHashMap();
        String name = authentication.getName();
        response.put("username", name);
 
        Object principal = authentication.getPrincipal();
        UserJwt userJwt = null;
        if(principal instanceof  UserJwt){
            userJwt = (UserJwt) principal;
        }else{
            //refresh_token默认不去调用userdetailService获取用户信息,这里我们手动去调用,得到 UserJwt
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);
            //userJwt = (UserJwt) userDetails;
            userJwt = new UserJwt(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
        }
        response.put("nickname", userJwt.getNickname());
        response.put("userId", userJwt.getUserId());
        response.put("userType",userJwt.getUserType());
        response.put("userPic",userJwt.getUserPic());
        response.put("password", userJwt.getPassword());
        response.put("menus", userJwt.getMenus());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
 
        return response;
    }
 
 
}