我要添加什么新字段"租户"用户详细信息以在@PostAuthorize中使用它。 在@PostAuthorize(" returnObject == principal.tenant")我收到错误:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/sectst] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression 'returnObject == principal.tenant'] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 26): Field or property 'tenant' cannot be found on object of type 'org.springframework.security.core.userdetails.User'
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:216)
无法理解为什么它通过默认的User类而不是我的自定义ExtendedUser
我的自定义用户类
public class ExtendedUser extends User {
private static final long serialVersionUID = 3149421282945554897L;
private final String tenant;
public ExtendedUser(String username, String password,
Collection<? extends GrantedAuthority> authorities, String tenant) {
super(username, password, authorities);
this.tenant = tenant;
}
public ExtendedUser(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, String tenant) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
this.tenant = tenant;
}
public String getTenant() {
return tenant;
}
}
自定义用户详细信息
public class ExtendedJdbcUserDetailsService extends JdbcDaoImpl {
private String extendedUsersByUsernameQuery;
public String getExtendedUsersByUsernameQuery() {
return extendedUsersByUsernameQuery;
}
public void setExtendedUsersByUsernameQuery(String extendedUsersByUsernameQuery) {
this.extendedUsersByUsernameQuery = extendedUsersByUsernameQuery;
}
@Override
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(extendedUsersByUsernameQuery, new String[] {username}, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
String tenant = rs.getString(3);
boolean enabled = rs.getBoolean(4);
return new ExtendedUser(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES, tenant);
}
});
}
}
修改 我已经覆盖了createUserDetails方法,它解决了问题
@Override
protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery,
List<GrantedAuthority> combinedAuthorities) {
String returnUsername = userFromUserQuery.getUsername();
return new ExtendedUser(returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
true, true, true, combinedAuthorities, ((ExtendedUser) userFromUserQuery).getTenant());
}