Testing session invalidation in Spring Security











up vote
2
down vote

favorite
2












I am playing around with Spring Security and now I am trying get some knowledge about testing my REST-controller with regards to security.



So I prepared my test-class with:



@Autowired
private WebApplicationContext context;

private MockMvc mvc;

@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}


containing test-cases mostly of the following or similar form:



@Test
public void handleSecuredRequest_shouldReturn200_withAdminUser() throws Exception{
ResultActions action = mvc.perform(get("/secured").with(user("admin").roles("ADMIN")));

int status = action.andReturn().getResponse().getStatus();
assertTrue("expected status code = 200 ; current status code = " + status, status == 200);
}


What I was not able to achieve until now were things concerning sessions.
Most notably I would be interested to verify that session-invalidation is performed correctly.



How can I achieve that?





EDIT:



I was able to find something close to a solution doing the following based on
https://stackoverflow.com/a/26281932/6294605 :



@Test
public void logout_shouldInvalidateSession_withLoggedInUser() throws Exception{
ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();

ResultActions action2 = mvc.perform(post("/logout").session(session));

ResultActions action3 = mvc.perform(get("/userAsJSON").session(session));
int status3 = action3.andReturn().getResponse().getStatus();

assertTrue("expected status code = 401 ; current status code = " + status3, status3 == 401);
}


But I am not entirely satisfied with this.




  1. It requires to process several steps to let me test what I want.

  2. Resulting from 1.: it is not detached from certain other things to function correctly (e.g. the "/userAsJSON" endpoint returning 401 for not authenticated users).

  3. Resulting from 2.: it requires additional attention to make sure that test-cases exist that ensure that the formal requirements for my test to be valid are met.


So I would wish for an option to make this less error-prone.



Any ideas?










share|improve this question




























    up vote
    2
    down vote

    favorite
    2












    I am playing around with Spring Security and now I am trying get some knowledge about testing my REST-controller with regards to security.



    So I prepared my test-class with:



    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
    mvc = MockMvcBuilders
    .webAppContextSetup(context)
    .apply(springSecurity())
    .build();
    }


    containing test-cases mostly of the following or similar form:



    @Test
    public void handleSecuredRequest_shouldReturn200_withAdminUser() throws Exception{
    ResultActions action = mvc.perform(get("/secured").with(user("admin").roles("ADMIN")));

    int status = action.andReturn().getResponse().getStatus();
    assertTrue("expected status code = 200 ; current status code = " + status, status == 200);
    }


    What I was not able to achieve until now were things concerning sessions.
    Most notably I would be interested to verify that session-invalidation is performed correctly.



    How can I achieve that?





    EDIT:



    I was able to find something close to a solution doing the following based on
    https://stackoverflow.com/a/26281932/6294605 :



    @Test
    public void logout_shouldInvalidateSession_withLoggedInUser() throws Exception{
    ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
    MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();

    ResultActions action2 = mvc.perform(post("/logout").session(session));

    ResultActions action3 = mvc.perform(get("/userAsJSON").session(session));
    int status3 = action3.andReturn().getResponse().getStatus();

    assertTrue("expected status code = 401 ; current status code = " + status3, status3 == 401);
    }


    But I am not entirely satisfied with this.




    1. It requires to process several steps to let me test what I want.

    2. Resulting from 1.: it is not detached from certain other things to function correctly (e.g. the "/userAsJSON" endpoint returning 401 for not authenticated users).

    3. Resulting from 2.: it requires additional attention to make sure that test-cases exist that ensure that the formal requirements for my test to be valid are met.


    So I would wish for an option to make this less error-prone.



    Any ideas?










    share|improve this question


























      up vote
      2
      down vote

      favorite
      2









      up vote
      2
      down vote

      favorite
      2






      2





      I am playing around with Spring Security and now I am trying get some knowledge about testing my REST-controller with regards to security.



      So I prepared my test-class with:



      @Autowired
      private WebApplicationContext context;

      private MockMvc mvc;

      @Before
      public void setup() {
      mvc = MockMvcBuilders
      .webAppContextSetup(context)
      .apply(springSecurity())
      .build();
      }


      containing test-cases mostly of the following or similar form:



      @Test
      public void handleSecuredRequest_shouldReturn200_withAdminUser() throws Exception{
      ResultActions action = mvc.perform(get("/secured").with(user("admin").roles("ADMIN")));

      int status = action.andReturn().getResponse().getStatus();
      assertTrue("expected status code = 200 ; current status code = " + status, status == 200);
      }


      What I was not able to achieve until now were things concerning sessions.
      Most notably I would be interested to verify that session-invalidation is performed correctly.



      How can I achieve that?





      EDIT:



      I was able to find something close to a solution doing the following based on
      https://stackoverflow.com/a/26281932/6294605 :



      @Test
      public void logout_shouldInvalidateSession_withLoggedInUser() throws Exception{
      ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
      MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();

      ResultActions action2 = mvc.perform(post("/logout").session(session));

      ResultActions action3 = mvc.perform(get("/userAsJSON").session(session));
      int status3 = action3.andReturn().getResponse().getStatus();

      assertTrue("expected status code = 401 ; current status code = " + status3, status3 == 401);
      }


      But I am not entirely satisfied with this.




      1. It requires to process several steps to let me test what I want.

      2. Resulting from 1.: it is not detached from certain other things to function correctly (e.g. the "/userAsJSON" endpoint returning 401 for not authenticated users).

      3. Resulting from 2.: it requires additional attention to make sure that test-cases exist that ensure that the formal requirements for my test to be valid are met.


      So I would wish for an option to make this less error-prone.



      Any ideas?










      share|improve this question















      I am playing around with Spring Security and now I am trying get some knowledge about testing my REST-controller with regards to security.



      So I prepared my test-class with:



      @Autowired
      private WebApplicationContext context;

      private MockMvc mvc;

      @Before
      public void setup() {
      mvc = MockMvcBuilders
      .webAppContextSetup(context)
      .apply(springSecurity())
      .build();
      }


      containing test-cases mostly of the following or similar form:



      @Test
      public void handleSecuredRequest_shouldReturn200_withAdminUser() throws Exception{
      ResultActions action = mvc.perform(get("/secured").with(user("admin").roles("ADMIN")));

      int status = action.andReturn().getResponse().getStatus();
      assertTrue("expected status code = 200 ; current status code = " + status, status == 200);
      }


      What I was not able to achieve until now were things concerning sessions.
      Most notably I would be interested to verify that session-invalidation is performed correctly.



      How can I achieve that?





      EDIT:



      I was able to find something close to a solution doing the following based on
      https://stackoverflow.com/a/26281932/6294605 :



      @Test
      public void logout_shouldInvalidateSession_withLoggedInUser() throws Exception{
      ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
      MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();

      ResultActions action2 = mvc.perform(post("/logout").session(session));

      ResultActions action3 = mvc.perform(get("/userAsJSON").session(session));
      int status3 = action3.andReturn().getResponse().getStatus();

      assertTrue("expected status code = 401 ; current status code = " + status3, status3 == 401);
      }


      But I am not entirely satisfied with this.




      1. It requires to process several steps to let me test what I want.

      2. Resulting from 1.: it is not detached from certain other things to function correctly (e.g. the "/userAsJSON" endpoint returning 401 for not authenticated users).

      3. Resulting from 2.: it requires additional attention to make sure that test-cases exist that ensure that the formal requirements for my test to be valid are met.


      So I would wish for an option to make this less error-prone.



      Any ideas?







      java spring spring-security






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 7 at 8:28

























      asked Nov 6 at 8:55









      Wolfone

      382312




      382312





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53168562%2ftesting-session-invalidation-in-spring-security%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53168562%2ftesting-session-invalidation-in-spring-security%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini