springsecurity5测试@webmvctest测试继续给出0302响应

yks3o0rb  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(357)

我正在编写一个示例springsecurity5程序。我使用awscognito作为oauth2提供者。我使用的流程是授权授予。当我在本地运行时,一切正常。我的rest端点得到了正确的保护,当我输入凭据时,我可以访问这些端点。
现在我想用切片测试来测试这个控制器。
我写了一封信 @WebMvcTest 然而,为了测试这个,我不断得到302个答案。在日志中,我看到请求被重定向到cognito。我的理解是,测试期间不会将请求发送给aws。请有人能解释一下为什么会这样,或者我哪里出了问题。
birdcontroller.java文件

@RestController
@RequestMapping(path = "/")
public class BirdController {

    @Autowired
    BirdService service;

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    List<Bird> getBirds(){
        return service.getAllBirds();
    }

WebSecurity配置.class

@Configuration
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

        private final String clientId;
        private final String logoutUrl;

        public WebSecurityConfiguration(@Value("${spring.security.oauth2.client.registration.cognito.clientId}") String clientId,
                                 @Value("${cognito.logoutUrl}") String logoutUrl) {
            this.clientId = clientId;
            this.logoutUrl = logoutUrl;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf()
                    .and()
                    .authorizeRequests(authorize ->
                            authorize.mvcMatchers("/").permitAll()
                                    .anyRequest().authenticated())
                    .oauth2Login()
                    .and()
                    .logout();

        }
    }

BirdController测试.java

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BirdController.class)
public class BirdControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BirdService service;

    @Test
    @WithAnonymousUser
    public void testGetAllBirds() throws Exception {
        this.mockMvc
                .perform(get("/"))
                .andExpect(status().isUnauthorized());
    }

我希望测试通过,但用户没有通过身份验证,但我得到302响应。
日志片段

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /
       Parameters = {}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/]}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 302
    Error message = null
          Headers = [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", Location:"http://localhost/oauth2/authorization/cognito"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = http://localhost/oauth2/authorization/cognito
          Cookies = []

java.lang.AssertionError: Status 
Expected :401
Actual   :302
 <Click to see difference>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)

aws cognito配置

spring:
    security:
        oauth2:
          client:
            registration:
              cognito:
                clientId: XXXX
                clientSecret: XXXXX
                scope: openid
                redirectUriTemplate: http://localhost:8080/login/oauth2/code/cognito
                clientName: XXXX
            provider:
              cognito:
                issuerUri: XXXX
                user-name-attribute: cognito:username

pom.xml文件

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

我已经花了3天的时间在这上面,把我的头发撕成碎片。已经查过其他问题,但没有帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题