Spring安全角色无法转换为授予权限

时间:2015-09-18 18:07:13

标签: java spring spring-mvc spring-security

User.java

public class User implements Serializable{
    @Id
    @Size(min=5,max=15)
    @Column(name="username", unique=true)
    private String username;

    @OneToMany(mappedBy="user")
    private Collection<Role> roles;

public User(User user) {
        this.username=user.username;
        this.roles=user.getRoles();
    }
}

Role.java

public class Role implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    private String role;

    @ManyToOne
    @JoinColumn(name="username")
    private User user;
}

UserServiceImpl.java

public class UserServiceImpl implements UserServiceDetails {

    private UserRepo userRepo;

    @Autowired
    public void setUserRepo(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        User user=userRepo.findUserByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }
        CustomUser customUser=new CustomUser(user);
        return customUser;
    }

    public final static class CustomUser extends User implements UserDetails
    {
        public CustomUser(User user) {
            super(user);
        }

        @SuppressWarnings("unchecked")
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            List<GrantedAuthority> authorities =
                    new ArrayList<GrantedAuthority>();
            authorities.addAll((Collection<? extends GrantedAuthority>) getRoles());

            return authorities;
        }

        @Override
        public boolean isAccountNonExpired() {
            return true;
        }

        @Override
        public boolean isAccountNonLocked() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }

    }

}

SecurityCOnfig.java

public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth
            .userDetailsService(userDetailsService); 
    }
}

错误: 角色无法转换为org.springframework.security.core.GrantedAuthority 我的角色表包含​​表单字符串“user”,“admin”等

中的角色

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:3)

正如Denium所说,转换不会像在代码中那样完成。我通过循环遍历每个角色来做类似的事情,如下所示:

authorities = new HashSet<GrantedAuthority>(roles.size());

for (String role : roles)
    authorities.add(new SimpleGrantedAuthority("ROLE_" + role));