使用HTTP标头的Spring Security

Cha*_*lah 6 security authentication spring-security http-headers spring-boot

我正在尝试为我的Spring Boot应用程序添加安全性.我当前的应用程序是使用REST控制器,每次我收到GETPOST请求时,我都会读取HTTP标头以检索用户和密码,以便根据我存储了所有用户的属性文件验证它们.我想将此更改为使用Spring Security,这是我到目前为止所得到的:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/index.html").permitAll()
            .antMatchers("/swagger-ui.html").hasRole("ADMIN")
            .anyRequest().authenticated();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("admin").password("password").roles("ADMIN").build());
    }
}
Run Code Online (Sandbox Code Playgroud)

如何告诉configure方法从头部而不是登录表单中检索用户凭据?

sha*_*haf 9

添加的最少代码是定义一个过滤器并将其添加到安全配置中,例如

XHeaderAuthenticationFilter.java

@Component
public class XHeaderAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String xAuth = request.getHeader("X-Authorization");

        User user = findByToken(xAuth);

        if (user == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token invalid");
        } else {
            final UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);

            filterChain.doFilter(request, response);
        }
    }

    //need to implement db user validation...
    private User findByToken(String token) {
        if (!token.equals("1234"))
            return null;

        final User user = new User(
                "username",
                "password",
                true,
                true,
                true,
                true,
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));

        return user;
    }
}
Run Code Online (Sandbox Code Playgroud)

安全配置.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(final HttpSecurity http) throws Exception {
            http.sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .exceptionHandling()
                    .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and()
                .addFilterBefore(new XHeaderAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用 springAOP来定义在进入带注释的控制器方法之前执行的某些逻辑的注释


jlu*_*etu 5

您应该避免使用默认值,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter因为它从您的请求参数中获取客户端提供的用户名和密码,而您确实需要从标头中获取它们。

因此,您应该编写一个自定义AuthenticationFilter扩展引用UsernamePasswordAuthenticationFilter来更改其行为以满足您的要求:

public class HeaderUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  public HeaderUsernamePasswordAuthenticationFilter() {
    super();
    this.setFilterProcessesUrl("/**");
    this.setPostOnly(false);
  }

  /* (non-Javadoc)
   * @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#obtainPassword(javax.servlet.http.HttpServletRequest)
   */
  @Override
  protected String obtainPassword(HttpServletRequest request) {
    return request.getHeader(this.getPasswordParameter());
  }

  /* (non-Javadoc)
   * @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#obtainUsername(javax.servlet.http.HttpServletRequest)
   */
  @Override
  protected String obtainUsername(HttpServletRequest request) {
    return request.getHeader(this.getPasswordParameter());
  }

}
Run Code Online (Sandbox Code Playgroud)

此过滤器示例扩展org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter侦听每个请求usernamepassword从头而不是parameters.

然后您应该以这种方式更改配置,将过滤器设置在以下UsernamePasswordAuthenticationFilter位置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterAt(
                new HeaderUsernamePasswordAuthenticationFilter(), 
                UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers("/index.html").permitAll()
            .antMatchers("/swagger-ui.html").hasRole("ADMIN")
            .anyRequest().authenticated();

}
Run Code Online (Sandbox Code Playgroud)


gla*_*tor -2

在 Spring Boot 应用程序中,您可以将以下内容添加到 application.properties

security.user.name=user
security.user.password=password
Run Code Online (Sandbox Code Playgroud)

它将完成其余的事情,例如从标头获取它并验证更多信息,请访问https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html