那些年SpringSecurity踩过的坑 GrantedAuthority

402 阅读1分钟

前言

在我学习springsecurity的过程中使用它进行用户授权时出现了几个错误,这几个错误有json异常Could not read JSON,其实就是继承的UserDetail类的json的反序列化失败和userdetail的修改。

问题一

引起第一问题的原因是securuty中的GrantedAuthority 是不能被序列化的,虽然报错中提示的是没有set方法,但是我加了也没有效果。学习过程中使用的 @JSONField(serialize = false)还是没能解决。最后使用了@JsonIgnore成功解决。

image.png

代码

@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
    //存储SpringSecurity所需要的权限信息的集合
    Collection<? extends GrantedAuthority> authorities;

问题二

由于我们需要在继承的UserDetail类中添加我们自己的用户实体类user和权限集合 permissions,所以还是会报json序列化失败,所以我们还需要在类上添加 @JsonIgnoreProperties(ignoreUnknown = true)来忽略类中不存在的字段

image.png

代码

@JsonIgnoreProperties(ignoreUnknown = true)
public class SecurityUser implements UserDetails {

    private User user;

    //存储权限信息
    private List<String> permissions;

问题三

记得把账户过期和锁定的这些改为true,不然会报Spring Security AccountExpiredException: User account has expired等异常

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

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

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

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