spring - 在 Spring Security 中实现 Basic Auth 后总是收到 401 错误

标签 spring spring-boot spring-security

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

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

@RequestMapping("/foo/")

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

接下来,我正在配置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
(我在上面的屏幕截图中隐藏了基本 URL)

最佳答案

编辑

别忘了制作 SecurityConfiguration工作。

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

关于spring - 在 Spring Security 中实现 Basic Auth 后总是收到 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228917/

相关文章:

java - Spring中的动态@Value等价物?

java - 使用 Spring Boot/JPA 生成唯一字段的正确方法是什么?

java - Postgresql 的 Liquibase addAutoIncrement 错误

java - Spring Security - 我如何直接调用访问控制方法?

使用 mongodb 进行 Spring session 复制未按预期工作

spring - 通过 spring LDAP 进行身份验证,并在数据库中进行额外的安全检查

使用 Spring + Hibernate 创建 MySQL 表

spring-boot - 我在查询 dsl jpa 实体将 dto 转换为 map 时遇到问题

java - Spring测试注解

Spring security - 为什么 RoleVoter 支持所有类而 WebExpressionVoter 只支持 FilterInvocation 的子类?