Home > Back-end >  How to test secured end-points in Spring application using JUnit?
How to test secured end-points in Spring application using JUnit?

Time:10-08

I am using JWT based authentication in my Spring project and I was trying to write JUnit Test cases for the secured end-points though I am not able to test it and getting

org.opentest4j.AssertionFailedError: Expected :201 Actual :403

My Security Config file is :

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ScopeMapping extends WebSecurityConfigurerAdapter {
    @Autowired
    XsuaaServiceConfiguration xsuaaServiceConfiguration;
    private static final String VT_SCOPE = "VT";
    private static final String DEVELOPER_SCOPE = "Developer";
    private static final String USER_SCOPE = "User";
    private static final String ADMIN_SCOPE = "Admin";
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                .headers()
                .contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/");
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .mvcMatchers(HttpMethod.GET,"/health").permitAll()
                .mvcMatchers("/v2/api-docs/**", "/swagger-ui.html", "/swagger-ui/**", "/swagger-resources/**").permitAll()
                .mvcMatchers("/v1/**").hasAuthority(VT_SCOPE)
                .mvcMatchers("/v2/**").permitAll()
                .mvcMatchers("/user/**").hasAnyAuthority(VT_SCOPE, ADMIN_SCOPE, USER_SCOPE, DEVELOPER_SCOPE)
                .mvcMatchers("/admin/**").hasAnyAuthority(VT_SCOPE, ADMIN_SCOPE, DEVELOPER_SCOPE)
                .mvcMatchers("/vt/**").hasAnyAuthority(VT_SCOPE, DEVELOPER_SCOPE)
                .anyRequest().denyAll()
                .and()
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(getJwtAuthenticationConverter());
    }
    Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() {
        TokenAuthenticationConverter converter = new TokenAuthenticationConverter(xsuaaServiceConfiguration);
        converter.setLocalScopeAsAuthorities(true);
        return converter;
    }
}

Test-case

@WithUserDetails(value="ram",userDetailsServiceBeanName = "secureBean")
    public void addForumTest() throws Exception {
        //  ForumQuery forumQuery = new ForumQuery("1","Query 1","Query 1 Desc","1",currentTime,replies,forumLikes);
        ForumQueryDto forumQueryDto = new ForumQueryDto("1","Query 1","Query 1 Desc",userDto,currentTime,repliesDto);
        Mockito.when(forumService.insertQuery(Mockito.any(ForumQueryDto.class))).thenReturn(forumQueryDto);
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user/forum/add")
                .contentType("application/json")
//                .header(HttpHeaders.AUTHORIZATION,<JWT-TOKEN>)
                .content(objectMapper.writeValueAsString(forumQueryDto)))
                .andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
    }

Custom-Bean

@Bean("secureBean")
    public UserDetailsService userDetailsService() {
        GrantedAuthority authority = new SimpleGrantedAuthority("VT_SCOPE");
        GrantedAuthority authority1 = new SimpleGrantedAuthority("ADMIN_SCOPE");
        GrantedAuthority authority2 = new SimpleGrantedAuthority("USER_SCOPE");
        GrantedAuthority authority3 = new SimpleGrantedAuthority("DEVELOPER_SCOPE");
        UserDetails userDetails = (UserDetails) new User("ram", "ram123", Arrays.asList(authority
                , authority1, authority2, authority3));
        return new InMemoryUserDetailsManager(Arrays.asList(userDetails));
    }

CodePudding user response:

Please take a look here. Spring security comes with proper testing support. I have shared link for section dedicated to test support for Security.

Example:

@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void getMessageWithMockUserCustomUser() {
    String message = messageService.getMessage();
    ...
}

This is how you apply test annotations on a class.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public class WithMockUserTests {
}

CodePudding user response:

In the security configuration you have specified that any endpoints that match "/user/**" must have the authority "VT", "Admin", "User" or "Developer".

.mvcMatchers("/user/**").hasAnyAuthority(VT_SCOPE, ADMIN_SCOPE, USER_SCOPE, DEVELOPER_SCOPE)

However, in the test, the request is made with a user that has the authorities "VT_SCOPE", "ADMIN_SCOPE", "USER_SCOPE" and "DEVELOPER_SCOPE".
None of these authorities match the required authorities, which is why you see a 403 response.

Note that you can more robustly test JWT authentication, using the built-in jwt() RequestPostProcessor.

mvc
    .perform(post("/user/forum/add")
        .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_example"))));

You can find extensive details and examples in the Spring Security reference documentation.

  • Related