Spring boot 使用application.properties中的用户进行Spring内存引导安全
我有一个基本的Spring启动应用程序,它使用inMemoryAuthentication和代码中声明的授权用户列表:Spring boot 使用application.properties中的用户进行Spring内存引导安全,spring-boot,Spring Boot,我有一个基本的Spring启动应用程序,它使用inMemoryAuthentication和代码中声明的授权用户列表: @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("guest").password("{noop}guest123
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("guest").password("{noop}guest1234").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("{noop}password").roles("ADMIN");
}
我想将用户/角色列表移动到application.properties文件中,例如,对于管理员用户:
spring.security.user.name=admin
spring.security.user.password=password
spring.security.user.roles=ADMIN
然而,这似乎不起作用,因为我得到一个403错误。我错过了什么?
谢谢spring security只有一个默认用户, 您可以使用自定义属性提供其他属性
...
@Autowired
private ApplicationProperties properties;
...
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> builder = auth.inMemoryAuthentication();
properties.getUsers().forEach(user -> {
builder.withUser(user.getUsername()).password(user.getPassword()).roles((String[]) user.getRoles().toArray());
});
}
我希望这能帮助您据我所知,Spring不支持这一点。使用户成为管理员的唯一方法是将其角色更改为管理员。通常,如果存在后端数据库,则更新角色列并相应地映射相应的授权权限。
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
private final List<Users> users = new ArrayList<>();
public static class Users {
private String username;
private String password;
private List<String> roles;
public String getUsername() {
return username;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
}
public List<Users> getUsers() {
return users;
}
}
spring:
application:
name: MyApp
...
application:
users:
-
username: guest
password: guest1234
roles: USER
-
username: admin
password: password
roles: USER,ADMIN