Annotation Type WithMockAuthentication


  • @Target({METHOD,TYPE})
    @Retention(RUNTIME)
    @Inherited
    @Documented
    @WithSecurityContext(factory=Factory.class)
    public @interface WithMockAuthentication

    Populates SecurityContext with an Authentication Mock.

    Sample usage:
     @Test
     @WithMockAuthentication
     public demoDefaultUserNameAndAuthorities {
       // test as "user" granted with "ROLE_USER"
     }
    
     @Test
     @WithMockAuthentication(name = "Ch4mpy", authorities = { "ROLE_TESTER", "ROLE_AUTHOR" })
     public demoCustomUserNameAndAuthorities {
       // test as "Ch4mpy" granted with "ROLE_TESTER", "ROLE_AUTHOR"
     }
    
     @Test
     @WithMockAuthentication(JwtAuthenticationToken.class)
     public demoCustomAuthenticationImpl {
       final var jwt = mock(Jwt.class);
       when(jwt.getSubject()).thenReturn(auth.getName());
    
       final var auth = (JwtAuthenticationToken) SecurityContextHolder.getContext();
       when(auth.getPrincipal()).thenReturn(jwt);
    
       // test as "user" granted with "ROLE_USER", the Authentication in the SecurityContext being a JwtAuthenticationToken mock
     }
     
    Author:
    Jérôme Wacongne <ch4mp@c4-soft.com>
    • Optional Element Summary

      Optional Elements 
      Modifier and Type Optional Element Description
      String[] authorities  
      Class<? extends org.springframework.security.core.Authentication> authType  
      String name  
      org.springframework.security.test.context.support.TestExecutionEvent setupBefore
      Determines when the SecurityContext is setup.
      Class<? extends org.springframework.security.core.Authentication> value  
    • Element Detail

      • value

        @AliasFor("authType")
        Class<? extends org.springframework.security.core.Authentication> value
        Default:
        org.springframework.security.core.Authentication.class
      • authType

        @AliasFor("value")
        Class<? extends org.springframework.security.core.Authentication> authType
        Default:
        org.springframework.security.core.Authentication.class
      • name

        String name
        Default:
        "user"
      • authorities

        String[] authorities
        Default:
        {"ROLE_USER"}
      • setupBefore

        @AliasFor(annotation=org.springframework.security.test.context.support.WithSecurityContext.class)
        org.springframework.security.test.context.support.TestExecutionEvent setupBefore
        Determines when the SecurityContext is setup. The default is before TestExecutionEvent.TEST_METHOD which occurs during TestExecutionListener.beforeTestMethod(TestContext)
        Returns:
        the TestExecutionEvent to initialize before
        Default:
        org.springframework.security.test.context.support.TestExecutionEvent.TEST_METHOD