Java 当角色是JSON对象时使用hasAuthority
我很难检查用户的权限,因为角色是JSON对象的形式。我无法访问该角色。代码如下所示Java 当角色是JSON对象时使用hasAuthority,java,spring,spring-security,Java,Spring,Spring Security,我很难检查用户的权限,因为角色是JSON对象的形式。我无法访问该角色。代码如下所示 @PreAuthorize("hasAuthority({'\"roleId\":\"1\",\"roleName\":\"USER\"'})") @GET public List<String> find() { return "successfully accessed"; } @PreAuthorize(“hasAuthority({'\'roleId\':\'1\',\'roleNa
@PreAuthorize("hasAuthority({'\"roleId\":\"1\",\"roleName\":\"USER\"'})")
@GET
public List<String> find() {
return "successfully accessed";
}
@PreAuthorize(“hasAuthority({'\'roleId\':\'1\',\'roleName\':\'USER\'})”
@得到
公共列表查找(){
返回“成功访问”;
}
我不知道是否可以使用hasAuthority
指令
但是,如果您正在启动新的应用程序或有可能修改现有的角色处理,我建议您实现自定义角色映射器。
它可能是这样的:
@Bean
public GrantedAuthoritiesMapper myAuthoritiesMapper() {
return authorities -> {
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.map(s -> {
ObjectMapper mapper = new ObjectMapper();
Role role = mapper.readValue(s, Role.class);
//return roleName or custom string combination of id, name etc.
return role.getRoleName();
})
.map(SimpleGrantedAuthority::new)
.collect(toList());
};
}
以及您的角色bean类:
class Role {
private String roleId;
private String roleName;
//getters and setters
}
之后,您可以使用:
@预授权(“hasAuthority”(“角色用户”)
(例如
USER
USER roleName)我不知道是否可以使用hasAuthority
指令
但是,如果您正在启动新的应用程序或有可能修改现有的角色处理,我建议您实现自定义角色映射器。
它可能是这样的:
@Bean
public GrantedAuthoritiesMapper myAuthoritiesMapper() {
return authorities -> {
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.map(s -> {
ObjectMapper mapper = new ObjectMapper();
Role role = mapper.readValue(s, Role.class);
//return roleName or custom string combination of id, name etc.
return role.getRoleName();
})
.map(SimpleGrantedAuthority::new)
.collect(toList());
};
}
以及您的角色bean类:
class Role {
private String roleId;
private String roleName;
//getters and setters
}
之后,您可以使用:
@预授权(“hasAuthority”(“角色用户”)
(例如USER
USER roleName)