提取用户详细信息的Oauth-2身份验证需要CustomPrincipal对象

时间:2019-09-05 11:01:12

标签: spring-boot oauth-2.0 jwt authorization restful-authentication

我获得了此代码以在Spring Boot项目中实现身份验证。除了提取要进行身份验证的用户之外,其他一切工作都很好。我已经搜索过,找不到其他地方的解决方案。

public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {

    private final String EMAIL = "email";

    private Collection<? extends GrantedAuthority> defaultAuthorities;

    public void setDefaultAuthorities(String[] defaultAuthorities) {
        this.defaultAuthorities = AuthorityUtils
                .commaSeparatedStringToAuthorityList(StringUtils.arrayToCommaDelimitedString(defaultAuthorities));
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication userAuthentication) {
        Map<String, Object> response = new LinkedHashMap<String, Object>();
        response.put(USERNAME, userAuthentication.getName());

        if (userAuthentication.getAuthorities() != null && !userAuthentication.getAuthorities().isEmpty())
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(userAuthentication.getAuthorities()));

        return response;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME))
            return new UsernamePasswordAuthenticationToken(
                    new CustomPrincipal(map.get(USERNAME).toString(), map.get(EMAIL).toString()), "N/A",
                    getAuthorities(map));
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES))
            return defaultAuthorities;

        Object authorities = map.get(AUTHORITIES);

        if (authorities instanceof String)
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);

        if (authorities instanceof Collection)
            return AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));

        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}

除此方法片段外,其他部分均正常工作

@Override
        public Authentication extractAuthentication(Map<String, ?> map) {
            if (map.containsKey(USERNAME))
                return new UsernamePasswordAuthenticationToken(
                        new CustomPrincipal(map.get(USERNAME).toString(), map.get(EMAIL).toString()), "N/A",
                        getAuthorities(map));
            return null;
        }

我知道这是一个CustomPrincipal对象,该字符串作为USERNAME,EMAIL传递。如何传递正确的参数?

1 个答案:

答案 0 :(得分:0)

谢谢大家。问题是Lombok库创建构造函数失败,因此简单的答案是手动创建它们。

它完美地工作。 CustomPrincipal类需要具有一个接受两个自变量的构造函数,该自变量是隐式定义的,但在另一个类的类实例化中需要时不会被注入