Spring Security using HTTP headers

前端 未结 4 915
青春惊慌失措
青春惊慌失措 2021-02-14 12:05

I am trying to add security to my Spring Boot application. My current application is using REST controllers and every time I get a GET or POST request

4条回答
  •  攒了一身酷
    2021-02-14 13:07

    You should avoid using default org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter since it gets client supplied username and password from the parameters of your request and you really need to get them from the headers.

    So, you should write a custom AuthenticationFilter extending referred UsernamePasswordAuthenticationFilter to change its behaviour to fit your requirements:

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

    This filter example extends org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter listens to every request and gets username and password from headers instead of parameters.

    Then you should change the configuration this way, setting your filter in the UsernamePasswordAuthenticationFilter position:

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

提交回复
热议问题