【问题标题】:Spring Security test returns 401 (unauthorized)Spring Security 测试返回 401(未经授权)
【发布时间】:2017-05-26 12:32:53
【问题描述】:

在本文档Spring Security MVC Test 中描述了如何使用 Spring Security 测试安全资源。我按照提供的所有步骤操作,但访问受保护的资源仍然返回错误代码 401(未经授权)。

这是我的测试课

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
public class UserControllerTest {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .defaultRequest(
                    get("/api/users/1")
                            .with(user("test@test.com").password("test"))
                            .with(httpBasic("sc68", "adminpass"))
            )
            .apply(springSecurity())
            .build();
    }

    @Test
    public void testUnprotectedResource() throws Exception {
        mockMvc.perform(get("/api/articles"))
                .andExpect(status().isOk());
    }

    @Test
    public void testProtectedResource() throws Exception {
        mockMvc.perform(get("/api/users/1"))
                .andExpect(status().isOk());
    }
}

我的资源服务器配置:

@Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .antMatchers("/api/users/register").permitAll()
                .antMatchers("/api/articles").permitAll()
                .anyRequest().authenticated().and()
                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and(    )
            .csrf().disable()
}

如果您想查看整个项目,可以找到here。我已经尝试了不同的测试运行器以及教程中描述的所有内容,但我找不到如何在测试期间获得经过身份验证的用户的解决方案。

【问题讨论】:

    标签: java spring security spring-mvc spring-security


    【解决方案1】:

    我认为您不应该同时拥有user()httpBasic()user() 用于基于表单的身份验证,并将创建一个带有 UsernamePasswordAuthenticationToken 的 SecurityContext。 httpBasic 将创建一个 base64 编码的 Authentication 标头。

    您的安全配置似乎缺少httpBasic() 配置,在我看来好像没有配置安全机制,只是一些匹配器。可以看一个例子here

    【讨论】:

    • 我的 AuthorizationServerConfigurerAdapter 中有基本身份验证。从我的 Angular 应用程序中,我可以通过以下 URL 接收我的 AccessToken:localhost:8081/oauth/…"
    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2023-03-09
    • 2022-01-21
    • 2019-08-09
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多