Как имитировать аутентификацию JWT в модульном тесте Spring Boot?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как имитировать аутентификацию JWT в модульном тесте Spring Boot?

Сообщение Anonymous »

Я добавил аутентификацию JWT с использованием Auth0 в свой Spring Boot REST API, следуя этому примеру.
Теперь, как и ожидалось, мои ранее работающие модульные тесты Controller дают код ответа401 Unauthorized вместо 200 OK, поскольку я не передаю JWT в тестах.
Как я могу имитировать часть JWT/Аутентификация моих тестов REST-контроллера?

Класс модульного теста

@AutoConfigureMockMvc
public class UserRoundsControllerTest extends AbstractUnitTests {

private static String STUB_USER_ID = "user3";
private static String STUB_ROUND_ID = "7e3b270222252b2dadd547fb";

@Autowired
private MockMvc mockMvc;

private Round round;

private ObjectId objectId;

@BeforeEach
public void setUp() {
initMocks(this);
round = Mocks.roundOne();
objectId = Mocks.objectId();
}

@Test
public void shouldGetAllRoundsByUserId() throws Exception {

// setup
given(userRoundService.getAllRoundsByUserId(STUB_USER_ID)).willReturn(
Collections.singletonList(round));

// mock the rounds/userId request
RequestBuilder requestBuilder = Requests.getAllRoundsByUserId(STUB_USER_ID);

// perform the requests
MockHttpServletResponse response = mockMvc.perform(requestBuilder)
.andReturn()
.getResponse();

// asserts
assertNotNull(response);
assertEquals(HttpStatus.OK.value(), response.getStatus());
}

//other tests
}

Класс запросов (использовался выше)

public class Requests {

private Requests() {}

public static RequestBuilder getAllRoundsByUserId(String userId) {
return MockMvcRequestBuilders
.get("/users/" + userId + "/rounds/")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON);
}
}

Конфигурация безопасности Spring

/**
* Configures our application with Spring Security to restrict access to our API endpoints.
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${auth0.audience}")
private String audience;

@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;

@Override
public void configure(HttpSecurity http) throws Exception {
/*
This is where we configure the security required for our endpoints and setup our app to serve as
an OAuth2 Resource Server, using JWT validation.
*/

http.cors().and().csrf().disable().sessionManagement().
sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.mvcMatchers(HttpMethod.GET, "/users/**").authenticated()
.mvcMatchers(HttpMethod.POST, "/users/**").authenticated()
.mvcMatchers(HttpMethod.DELETE, "/users/**").authenticated()
.mvcMatchers(HttpMethod.PUT, "/users/**").authenticated()
.and()
.oauth2ResourceServer().jwt();
}

@Bean
JwtDecoder jwtDecoder() {
/*
By default, Spring Security does not validate the "aud" claim of the token, to ensure that this token is
indeed intended for our app. Adding our own validator is easy to do:
*/

NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
JwtDecoders.fromOidcIssuerLocation(issuer);

OAuth2TokenValidator audienceValidator = new AudienceValidator(audience);
OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator withAudience = new DelegatingOAuth2TokenValidator(withIssuer,
audienceValidator);

jwtDecoder.setJwtValidator(withAudience);

return jwtDecoder;
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

Абстрактный класс модульного теста

@ExtendWith(SpringExtension.class)
@SpringBootTest(
classes = PokerStatApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public abstract class AbstractUnitTests {
// mock objects etc
}


Подробнее здесь: https://stackoverflow.com/questions/615 ... -unit-test
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»