我有一个基于Spring Boot的REST Web服务。对于身份验证,我使用Spring Security和基本身份验证,对此我是新手。我的解决方案必须使用角色和权限吗?
我只希望Web服务的用户声明用户名和密码凭据。我在数据库或其他地方没有任何用户。
在我的WebSecurityConfigurerAdapter配置中,我现在在configureGlobal方法的末尾有.authorities("ROLE_USER");
,下面是Internet上的示例。我想跳过该类,以便该类看起来像这样:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username").password(passwordEncoder().encode("password"));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我发现我做不到。如果我改用.roles("USER")
,我可以工作。但是我既不想处理权限,也不希望处理角色,而只希望处理用户名和密码。为什么我需要这个或如何跳过呢?
我很高兴您能向新手介绍这个问题(身份验证和Spring Security)。
[如果使用inMemoryAuthentication
,通常通过roles("...")
提供角色InMemoryAuthentication不适用于null
作为GrantedAuthorities。
但是没有什么可以阻止您提供空白列表...
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username")
.password(passwordEncoder().encode("password"))
.roles(); // <--- leave roles empty
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
注意:不要以为您需要@EnableWebSecurity
或使用configureGlobal
...
或者您始终可以选择创建自己的自定义AuthenticationProvider。
自定义AuthenticationProvider的配置:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
@Bean
public AuthenticationProvider authProvider() {
return new CustomAuthenticationProvider();
}