- 不需要加入被序列化转换成json的对象属性的get方法上要加@JsonIgnore注解否则会报错 through reference chain: com.xxx.xxx.model.User["没加注解的属性"]
- 使用Jwts.builder()生成token后不能在token前后拼接字符串否则在token解析的时候会乱码:io.jsonwebtoken.MalformedJwtException: Unable to read JSON value: �z��'G�#�$�uB"�&�r#�$�3#Sb
- 在重写UserDetailsService的loadUserByUsername的方法时候要注意:
- 角色模型必须实现GrantedAuthority接口重写getAuthority方法(注意这个方法需要加@JsonIgnore注解)这个方法需要直接返回角色的名称
@JsonIgnore @Override public String getAuthority() { return name; } - 自定义的User模型实现接口UserDetails重写getAuthorities时候这个方法需要返回的就是每个用户的角色list
@JsonIgnore @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roleList; } public void setAuthorities(Collection<? extends GrantedAuthority> authorities) { this.roleList= (List<Role>) authorities; }
- 角色模型必须实现GrantedAuthority接口重写getAuthority方法(注意这个方法需要加@JsonIgnore注解)这个方法需要直接返回角色的名称
这个时候loadUserByUsername方法的自定义用户模型在设置Authorities的时候就可以直接放入角色模型(你的角色模型必须实现SimpleGrantedAuthority接口),如果你仅仅是放入new SimpleGrantedAuthority(role.getName())你在序列化和反序列化的时候就会Json序列化失败或者导致序列化出来的角色list会[Role{id=0, name='null'}, Role{id=0, name='null'}],直接不能使用访问任何需要认证的资源都会403,贴上我的方法
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { User user=userMapper.findByUsername(username); if (null==user){ return null; } //赋值给authorities角色名必须是ROLE_开头 List<Role> roleList=user.getRoleList(); user.setAuthorities(roleList); return user; }catch (Exception e){ e.printStackTrace(); return null; } }暂时就想起来这么多有继续踩坑再补
版权声明:本文为qq_37975021原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。