Код: Выделить всё
@GetMapping("/get-role")
public ResponseEntity getRole(Authentication auth) {
String role = auth.getAuthorities().stream().findFirst().get().toString();
return ResponseEntity.ok(role);
}
Код: Выделить всё
@Test
@DisplayName("Test Role")
@WithMockUser (username = "user", roles = {"Admin"})
void testRole() throws Exception {
URI uri = new URI("/v1/me/get-role");
mockRequest
.perform(MockMvcRequestBuilders.get(uri))
.andExpect(MockMvcResultMatchers.status().isOk());
}
Код: Выделить всё
jakarta.servlet.ServletException:
Request processing failed:
java.lang.NullPointerException:
Cannot invoke "org.springframework.security.core.Authentication.getAuthorities()" because "auth" is null
Код: Выделить всё
org.springframework.boot
spring-boot-starter-test
test
org.springframework.security
spring-security-test
test
Код: Выделить всё
@WebMvcTest(controllers = MyController.class)
@AutoConfigureMockMvc(addFilters = false)
@ContextConfiguration(classes = SecurityConfig.class)
@Import(MyController.class)
public class MyControllerTest {
// rest of code
}
Код: Выделить всё
User mockUser = Mockito.mock(User.class);
Authentication authentication = Mockito.mock(UsernamePasswordAuthenticationToken.class);
Mockito.when(authentication.getPrincipal()).thenReturn(mockUser);
Mockito.when(authentication.getCredentials()).thenReturn("password");
Mockito.when(authentication.isAuthenticated()).thenReturn(true);
Mockito.when(authentication.getAuthorities()).thenReturn((Collection) List.of(new SimpleGrantedAuthority("Admin")));
Код: Выделить всё
mockRequest
.perform(MockMvcRequestBuilders
.get(uri)
.with(SecurityMockMvcRequestPostProcessors
.user("user")
.authorities(new SimpleGrantedAuthority("Admin"))))
.andExpect(MockMvcResultMatchers.status().isOk());
Код: Выделить всё
mockRequest
.perform(MockMvcRequestBuilders
.get(uri)
.with(SecurityMockMvcRequestPostProcessors.jwt()))
.andExpect(MockMvcResultMatchers.status().isOk());
Код: Выделить всё
java.lang.NoClassDefFoundError:
org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter
Подробнее здесь: https://stackoverflow.com/questions/791 ... thmockuser
Мобильная версия