自定义GrantedAuthority

时间:2018-09-27 22:36:46

标签: spring spring-boot spring-security spring-security-oauth2

我创建了一个CustomGrantedAuthority,它实现了GrantedAuthority接口,如下所示:

CustomGrantedAuthority.java

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;

import com.eliza.tourism.ms.users.dao.model.ElizaTourismGroup;
import com.eliza.tourism.ms.users.dao.model.Role;

public class CustomGrantedAuthority implements GrantedAuthority {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    private ElizaTourismGroup group;

    public CustomGrantedAuthority(ElizaTourismGroup group) {
        Assert.notNull(group, "A granted authority group representation is required");
        this.group = group;
    }

    @Override
    public String getAuthority() {
        final JsonObjectBuilder groupJsonBuilder = Json.createObjectBuilder();
        if (!group.getRoles().isEmpty()) {
            final JsonArrayBuilder rolesArrayBuilder = Json.createArrayBuilder();
            for (Role role : group.getRoles()) {
                final JsonObjectBuilder roleJsonBuilder = Json.createObjectBuilder();
                final JsonArrayBuilder privilegesArrayBuilder = Json.createArrayBuilder();
                role.getPrivileges().stream().map(privilege -> privilege.getName()).forEach(privilegesArrayBuilder::add);
                roleJsonBuilder.add(role.getName(), privilegesArrayBuilder);
                rolesArrayBuilder.add(roleJsonBuilder);
            }
            groupJsonBuilder.add(group.getName(), rolesArrayBuilder);
            return groupJsonBuilder.build().toString();
        }
        return "";
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj instanceof CustomGrantedAuthority) {
            return group.getId().equals(((CustomGrantedAuthority) obj).group.getId());
        }

        return false;
    }

    @Override
    public int hashCode() {
        return this.group.getId().hashCode();
    }

    @Override
    public String toString() {
        return this.group.getId().toString();
    }
}

在我的实体中,我正在调用此瞬态方法:

@Transient
    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (groups != null && !groups.isEmpty())
            groups.stream().map(group -> new CustomGrantedAuthority(group)).forEach(authorities::add);
        return authorities;
    }
  

我的问题是春天忽略了这个,总是打电话    SimpleGrantedAuthority.java 且从不执行CustomGrantedAuthority.java类

那我该怎么做才能使身份验证器调用我的自定义类而不是SimpleGrantedAuthority.java类?

0 个答案:

没有答案