在Spring Security中实现Basic Auth后总是得到401错误

时间:2016-12-19 18:37:36

标签: spring spring-boot spring-security

我正在尝试使用Spring Security Annotations实现HTTP Basic Auth。

我有一个REST端点,定义如下:

@RequestMapping("/foo/")

我希望只有Admin角色的人才能访问/ foo / endpoint。

接下来,我正在配置Spring Security,如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
    private static String REALM="MY_TEST_REALM";
     
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("tom").password("abc123").roles("USER");
    }
     
    @Override
    protected void configure(HttpSecurity http) throws Exception {
  
      //http.csrf().disable()
      http  
      .authorizeRequests()
        .antMatchers("/foo/").hasRole("ADMIN")
        .and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//We don't need sessions to be created.
    }
     
    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
        return new CustomBasicAuthenticationEntryPoint();
    }
     
    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }
}

所以,我只想要密码为abc123的账号用户名才能调用REST端点。

接下来,我定义应该返回的错误

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
 
    @Override
    public void commence(final HttpServletRequest request, 
            final HttpServletResponse response, 
            final AuthenticationException authException) throws IOException, ServletException {
        //Authentication failed, send error response.
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
         
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 : " + authException.getMessage());
    }
     
    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("MY_TEST_REALM");
        super.afterPropertiesSet();
    }
}

我尝试使用Postman进行测试,我正在使用具有正确凭据的Basic Auth,但我总是得到401错误。我错过了任何一步吗?

请参阅Postman下面的截图。我错过任何标题吗? enter image description here

和,这里是标题部分 enter image description here (我在上面的屏幕截图中隐藏了基本网址)

1 个答案:

答案 0 :(得分:3)

修改

不要忘记让SecurityConfiguration工作。

@Import({ SecurityConfiguration.class })ComponentScan("<packageName>")