Spring Security,简单路由上的错误401

ao218c7q  于 2023-03-18  发布在  Spring
关注(0)|答案(1)|浏览(171)

我在Sping Boot 安全(v2.7.3)和Spring安全测试(v5.7.3)方面遇到了一些问题。
我不明白为什么我有一个错误401在一个简单的路线没有任何限制。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfigurer extends GlobalMethodSecurityConfiguration {
}
@RestController
public class TestController {
    @GetMapping("/test/test")
    public String helloTest() { return "Hello Test"; }

    @IsPermitToAll
    @GetMapping("/test/public")
    public String helloPublic() { return "Hello Public"; }

    @IsAdmin
    @GetMapping("/test/admin")
    public String helloAdmin() { return "Hello Admin"; }

    @IsUser
    @GetMapping("/test/user")
    public String helloUser() { return "Hello User"; }
}
@ExtendWith(SpringExtension.class)
@WebMvcTest(TestController.class)
@Import(MethodSecurityConfigurer.class)
class TestRoutes {
    @Autowired
    private MockMvc mvc;
    @Test
    void givenNoAuthentification_WhenRouteTest_ThenOK() throws Exception {
        mvc.perform(get("/test/test")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
    @Test
    void givenNoAuthentification_WhenRoutePublic_ThenOK() throws Exception {
        mvc.perform(get("/test/public")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
    @Test
    @WithAnonymousUser
    void givenAuthentifiedAnonymeUser_WhenRoutePublic_ThenOK() throws Exception {
        mvc.perform(get("/test/public")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
    @Test
    @WithMockUser(username = "test", roles = {"user"})
    void givenAuthentifiedUser_WhenRoutePublic_ThenOK() throws Exception {
        mvc.perform(get("/test/public")
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }

帮助真的很受欢迎,我坚持这种奇怪的行为。
我也不明白为什么允许所有的路由/测试/公共匿名或未经验证的用户不工作。
通常情况下,当访问该路由时,只有身份验证不好的用户才会面临401。而不是没有身份验证的用户,比如新访问者,对吗?
就像我看到的这个例子:Youtube tutorial
提前感谢您的关注。
对给定的无验证时路由测试时正常()的响应:

MockHttpServletResponse:
           Status = 401
    Error message = null
          Headers = [WWW-Authenticate:"Bearer", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
7ivaypg9

7ivaypg91#

@约翰威廉姆斯
以下是SecurityConfig文件的示例:

@Configuration

@启用WebSecurity公共类安全配置堆栈{

private static final Logger logger = LoggerFactory.getLogger(SecurityConfigurationStack.class);

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    logger.info("Configuring filter chain");
    http.authorizeRequests(authorizeRequests ->
        authorizeRequests
            // (...) List of routes with filters here
            .anyRequest().denyAll()        // Any URL that has not already been matched on is denied access
        )
        .oauth2ResourceServer(resourceServerConfigurer -> resourceServerConfigurer
            .jwt(jwtConfigurer -> jwtConfigurer
                .jwtAuthenticationConverter(jwtAuthenticationConverter()))
            );

    http.cors().and().csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return http.build();
}

}
因为我直接在方法上应用了过滤器,所以这里没有过滤器。

相关问题