首页 > 解决方案 > 没有角色和权限的 Web 服务的 Spring Security

问题描述

我有一个基于 Spring Boot 构建的 REST Web 服务。对于身份验证,我使用 Spring Security 和 Basic Authentication,我对此并不陌生。我是否必须为我的解决方案使用角色和权限?

我只希望 Web 服务的用户声明用户名和密码凭据。我在数据库或其他地方没有任何用户。

在我的 WebSecurityConfigurerAdapter 配置中,我现在.authorities("ROLE_USER");在我的 configureGlobal 方法的末尾,遵循互联网上的示例。我想跳过它,这样课程看起来像这样:

@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)向新手提供任何启示。

标签: restspring-bootweb-servicesspring-securitybasic-authentication

解决方案


如果您使用inMemoryAuthentication,您通常通过以下方式提供角色roles("...")

InMemoryAuthentication 不能null作为 GrantedAuthorities 使用。所以不打电话roles(...)会导致BeanCreationException

但是没有什么能阻止你提供一个空列表......比如:

@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();
    }


推荐阅读