I have a basic Spring Boot application which uses inMemoryAuthentication and a list of authorized users declared in the code:
@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");
}
I'd like to move the user/roles list into the application.properties file, for example for the admin user:
spring.security.user.name=admin
spring.security.user.password=password
spring.security.user.roles=ADMIN
However that does not seem to work as I'm getting a 403 error. What am I missing? Thanks
spring security has only one default user, you can provide others by using your custom properties
...
@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());
});
}
with your ApplicationProperties
@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;
}
}
and your.yaml file (yaml is less verbose than.properties files)
spring:
application:
name: MyApp
...
application:
users:
-
username: guest
password: guest1234
roles: USER
-
username: admin
password: password
roles: USER,ADMIN
I hope this can help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.