使用基本认证保护Spring Boot REST应用程序的安全性

3
我已经查阅了关于使用Spring Security的文章,但它们并不能完全满足我的需求。它们通常处理内存用户和明文密码。 我想要实现的目标: 客户端使用基本认证进行身份验证。
安全控制器方法如下所示:
  @RequestMapping(value = "/test")
  public ResponseEntity test(@AuthenticationPrincipal MyUser user){
      // Logic
  }

如果给定的用户已通过身份验证,则希望控制器方法在其参数中获取MyUser对象,否则为null。
我将用户的哈希密码和盐存储在数据库中,并且我有一个服务,用于验证给定的用户名密码对,并返回用户对象或null(如果验证成功或失败)。
现在需要拦截每个请求,查看基本身份验证标头,将信息传递给我的自定义身份验证服务,然后将其结果传递到控制器方法。不幸的是,我还没有能够做到这一点。
我阅读了有关使用自定义UserDetailsService的内容,但似乎仅处理从数据库中提取用户数据,而不涉及任何身份验证。我无法弄清如何将所有组件连接在一起。
您能指导我如何使这个相当简单的工作流程正常工作吗?
编辑
我没有使用XML配置,我唯一与安全相关的配置是:
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").csrf().disable();

        http.authorizeRequests()
                .antMatchers("/user").permitAll()
                .antMatchers("/user/**").permitAll()
                .anyRequest().authenticated();
    }
}

基本上,您要做的是将<http-basic />添加到<http>标签中(如果您正在使用XML样式配置)。为了得到更具体的答案,您可以在帖子中添加一些有关您的配置的详细信息。例如,配置文件/类和web.xml(如果有的话)。 - Stefano Cazzola
我没有使用XML配置,而是将其放在代码中。不过这并不复杂。我已经将它添加到问题中了。 - Martin Melka
2个回答

5

基本身份验证有三种不同的方式 -

1 - 只需添加spring-security maven依赖项

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

自动启用基本身份验证,例如用户名 -“user”,密码可以在控制台中找到,默认安全密码为“bdd42ed9-635d-422b-9430-ce463625fd2e”

2- 创建一个安全配置类,如下所示:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}

第三种方法是在application.properties文件中添加默认的用户名和密码,如下所示:

security.user.name=user
security.user.password=password

并创建如下代码所示的配置类
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

如果您仍有疑问,可以点击下方链接观看这个视频:

基本身份验证


1
你第一个代码块中的 private AuthenticationEntryPoint authEntryPoint 到底有什么用? - Rafael Eyng

3

那看起来很有前途,我会去看看它。 - Martin Melka
1
请勿仅回答一个链接的问题:http://meta.stackexchange.com/q/8231 为了提高您的答案质量,请在您的答案中包含相关部分的链接。 - JesperB
这在某种程度上有所帮助,但又引发了另一个问题 - https://dev59.com/25Xfa4cB1Zd3GeqPlua6 - Martin Melka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接