I’m facing a problem of incorrect testing results. Here is my test:
@AutoConfigureMockMvc
@SpringBootTest
class JwtAuthenticationAndAuthorizationWithTestsApplicationTests {
private static final String USER_NAME = "test";
private static final String ADMIN_NAME = "[email protected]";
private static final String PASSWORD = "test";
@Autowired
private MockMvc mvc;
@Test
@WithMockUser(username = "testerUsername", roles = {"USER"})
public void testAdminEndpointUnauthorized() throws Exception {
mvc.perform(get("/api/v1/test/mod")).andExpect(status().isUnauthorized());
}
}
Result:
java.lang.AssertionError: Status expected:<401> but was:<403>
Expected :401
Actual :403
My security config:
@Bean
public Http401UnauthorizedEntryPoint authenticationEntryPoint(){
return new Http401UnauthorizedEntryPoint();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.exceptionHandling(exception -> exception
.authenticationEntryPoint(authenticationEntryPoint()))
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize ->
authorize.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/api/v1/test/all").permitAll()
.anyRequest().authenticated());
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authTokenFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
And Http401UnauthorizedEntryPoint implementation:
@Component
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
private final Logger log = LoggerFactory.getLogger(Http401UnauthorizedEntryPoint.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
ServletException, IOException {
log.debug("Pre-authenticated entry point called. Rejecting access");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}
I have tried this solution, but it didn’t work for me.
I don’t understand why I get 401 response status when manually checking entry points with Postman and 403 with junit testing
New contributor
Nazar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.