【问题标题】:Spring Security for web service without roles and authorities [closed]没有角色和权限的 Web 服务的 Spring Security [关闭]
【发布时间】:2020-06-01 13:55:58
【问题描述】:

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

我只希望 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)向新手提供任何启示。

【问题讨论】:

标签: rest spring-boot web-services spring-security basic-authentication


【解决方案1】:

如果您使用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();
    }

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 2011-12-24
    • 2018-12-30
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2012-10-24
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多