Spring Boot中使用自定义令牌进行身份验证

Shu*_*ana 4 spring spring-security spring-boot spring-rest

我需要保护我的 Spring Boot 应用程序,这就是我所拥有的:

  1. 一个 Spring Boot 应用程序,公开了一些 REST API。
  2. 与公开的 api 通信的前端。
  3. 前端发送用于身份验证的自定义身份验证令牌。
  4. 存储自定义身份验证令牌的数据库。

因此,本质上我的前端将向我的 Spring Boot 应用程序发送一个休息请求以及身份验证令牌,并且我的 Spring Boot 应用程序将查询数据库以查看身份验证令牌是否有效。

此身份验证应该适用于我的 Spring Boot 应用程序中的所有控制器。有没有一种方法可以默认为每个休息请求执行此操作,而无需在每个控制器中显式放置身份验证?

我了解 Spring Boot Web 安全功能,但没有足够的信息来说明如何将这些功能与自定义令牌一起使用。

sle*_*ine 6

spring-security 绝对是最佳选择。对于 Spring Boot,请使用以下启动器:

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
   </dependency>
Run Code Online (Sandbox Code Playgroud)

然后,您必须在某些配置类中定义安全配置,例如:

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   private final BaseTokenService tokenService;

    @Bean
    public TokenAuthenticationService tokenAuthenticationService() {
        return new TokenAuthenticationServiceImpl(tokenService);
    }

    @Bean
    public TokenAuthenticationProvider tokenAuthenticationProvider() {
        return new TokenAuthenticationProvider(tokenAuthenticationService());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(tokenAuthenticationProvider());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        TokenAuthenticationFilter tokenAuthenticationFilter = new TokenAuthenticationFilter(super.authenticationManager(), false);

        //session management
        http
                .anonymous().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();

        //filter
        http
                .antMatcher("/api/secured/**")
                .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }

}
Run Code Online (Sandbox Code Playgroud)

正如您在上面的配置中看到的,我使用了自定义身份验证过滤器(tokenAuthenticationFilter)。它可能是您可以用来处理第三条语句的安全过滤器:前端发送用于身份验证的自定义身份验证令牌。它附带了一个 AuthenticationProvider,这是一个 Spring Security 组件,它根据安全过滤器提取的令牌来验证用户身份验证。您必须根据您的需要提供所有 Token* 类的正确实现。

“我了解 Spring Boot Web 安全功能,但没有足够的信息来说明如何将这些功能与自定义令牌一起使用。”

Spring Security 文档应该是这样的:

https://docs.spring.io/spring-security/site/docs/4.2.5.RELEASE/reference/htmlsingle/

如果您想要示例教程:

https://www.sylvainlemoine.com/2016/06/06/spring-saml2.0-websso-and-jwt-for-mobile-api/

跳过 saml 部分,它在这里无关紧要,但请查看 JWT(Json Web Token)部分,它应该能够满足您的用例。