org.springframework.security.test.context.support.WithMockUser类的使用及代码示例

x33g5p2x  于2022-02-03 转载在 其他  
字(14.0k)|赞(0)|评价(0)|浏览(147)

本文整理了Java中org.springframework.security.test.context.support.WithMockUser类的一些代码示例,展示了WithMockUser类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WithMockUser类的具体详情如下:
包路径:org.springframework.security.test.context.support.WithMockUser
类名称:WithMockUser

WithMockUser介绍

暂无

代码示例

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void globalMethodSecurityConfigurationAutowiresPermissionEvaluator() {
  this.spring.register(AutowirePermissionEvaluatorConfig.class).autowire();
  PermissionEvaluator permission = this.spring.getContext().getBean(PermissionEvaluator.class);
  when(permission.hasPermission(any(), eq("something"), eq("read"))).thenReturn(true, false);
  this.service.hasPermission("something");
  // no exception
  assertThatThrownBy(() -> this.service.hasPermission("something"))
    .isInstanceOf(AccessDeniedException.class);
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void registeredOAuth2AuthorizedClientWhenAuthenticatedThenRedirects() {
  this.spring.register(Config.class, AuthorizedClientController.class).autowire();
  ReactiveClientRegistrationRepository repository = this.spring.getContext()
      .getBean(ReactiveClientRegistrationRepository.class);
  ServerOAuth2AuthorizedClientRepository authorizedClientRepository = this.spring.getContext().getBean(ServerOAuth2AuthorizedClientRepository.class);
  when(repository.findByRegistrationId(any())).thenReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
  when(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty());
  this.client.get().uri("/")
    .exchange()
    .expectStatus().is3xxRedirection();
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() {
  this.spring.register(CustomTrustResolverConfig.class).autowire();
  AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
  when(trustResolver.isAnonymous(any())).thenReturn(true, false);
  assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous())
    .isInstanceOf(AccessDeniedException.class);
  this.service.preAuthorizeNotAnonymous();
  verify(trustResolver, atLeastOnce()).isAnonymous(any());
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void contextRefreshWhenUsingAspectJThenAutowire() throws Exception {
  this.spring.register(AspectJModeConfig.class, MethodSecurityServiceConfig.class).autowire();
  assertThat(this.spring.getContext().getBean(Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect"))).isNotNull();
  assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
  //TODO diagnose why aspectj isn't weaving method security advice around MethodSecurityServiceImpl
}

代码示例来源:origin: org.springframework.security/spring-security-test

public SecurityContext createSecurityContext(WithMockUser withUser) {
  String username = StringUtils.hasLength(withUser.username()) ? withUser
      .username() : withUser.value();
  if (username == null) {
    throw new IllegalArgumentException(withUser
  for (String authority : withUser.authorities()) {
    grantedAuthorities.add(new SimpleGrantedAuthority(authority));
    for (String role : withUser.roles()) {
      if (role.startsWith("ROLE_")) {
        throw new IllegalArgumentException("roles cannot start with ROLE_ Got "
  } else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) {
    throw new IllegalStateException("You cannot define roles attribute "+ Arrays.asList(withUser.roles())+" with authorities attribute "+ Arrays.asList(withUser.authorities()));
  User principal = new User(username, withUser.password(), true, true, true, true,
      grantedAuthorities);
  Authentication authentication = new UsernamePasswordAuthenticationToken(

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to create a user for role 'ADMIN'")
@Test
@WithMockUser(authorities = "SCOPE_admin")
void verifyCreateAccessIsGrantedForAdmin() {
  when(userRepository.insert(Mockito.<Mono<User>>any())).thenReturn(Flux.just(new User(UUID.randomUUID(),
      "test@example.com", "Max", "Maier",
      Collections.singletonList(Role.USER))));
  StepVerifier.create(userService.create(Mono.just(new UserResource(UUID.randomUUID(),
      "test@example.com", "Max", "Maier",
      Collections.singletonList(Role.USER))))).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to borrow a book by id for role 'USER'")
@Test
@WithMockUser
void verifyBorrowByIdAccessIsGrantedForUser() {
 Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
 when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
 when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
 when(userRepository.findById(any(UUID.class))).thenReturn(
     Mono.just(new User(UUID.randomUUID(),"test@example.com", "secret", "Max",
         "Maier", Collections.singletonList(Role.USER))));
 StepVerifier.create(bookService.borrowById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
 verify(bookRepository).save(any());
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenProxyTargetClassThenDoesNotWireToInterface() {
  this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
  // make sure service was actually proxied
  assertThat(this.service.getClass().getInterfaces())
    .doesNotContain(MethodSecurityService.class);
  assertThatThrownBy(() -> this.service.preAuthorize())
    .isInstanceOf(AccessDeniedException.class);
}

代码示例来源:origin: apache/servicemix-bundles

public SecurityContext createSecurityContext(WithMockUser withUser) {
  String username = StringUtils.hasLength(withUser.username()) ? withUser
      .username() : withUser.value();
  if (username == null) {
    throw new IllegalArgumentException(withUser
  for (String authority : withUser.authorities()) {
    grantedAuthorities.add(new SimpleGrantedAuthority(authority));
    for (String role : withUser.roles()) {
      if (role.startsWith("ROLE_")) {
        throw new IllegalArgumentException("roles cannot start with ROLE_ Got "
  } else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) {
    throw new IllegalStateException("You cannot define roles attribute "+ Arrays.asList(withUser.roles())+" with authorities attribute "+ Arrays.asList(withUser.authorities()));
  User principal = new User(username, withUser.password(), true, true, true, true,
      grantedAuthorities);
  Authentication authentication = new UsernamePasswordAuthenticationToken(

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to return a book by id for role 'USER'")
@Test
@WithMockUser
void verifyReturnByIdAccessIsGrantedForUser() {
  Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
  when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
  when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
  when(userRepository.findById(any(UUID.class))).thenReturn(
      Mono.just(new User(UUID.randomUUID(), "test@example.com", "Max",
          "Maier", Collections.singletonList(Role.USER))));
  StepVerifier.create(bookService.returnById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to create a user for role 'ADMIN'")
@Test
@WithMockUser(roles = "ADMIN")
void verifyCreateAccessIsGrantedForAdmin() {
  when(userRepository.insert(Mockito.<Mono<User>>any())).thenReturn(Flux.just(new User(UUID.randomUUID(),
      "test@example.com", "Max", "Maier",
      Collections.singletonList(Role.USER))));
  StepVerifier.create(userService.create(Mono.just(new UserResource(UUID.randomUUID(),
      "test@example.com", "Max", "Maier",
      Collections.singletonList(Role.USER))))).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to borrow a book by id for role 'USER'")
@Test
@WithMockUser(authorities = "SCOPE_user")
void verifyBorrowByIdAccessIsGrantedForUser() {
  Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
  when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
  when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
  when(userRepository.findById(any(UUID.class))).thenReturn(
      Mono.just(new User(UUID.randomUUID(), "test@example.com", "Max",
          "Maier", Collections.singletonList(Role.USER))));
  StepVerifier.create(bookService.borrowById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
  verify(bookRepository).save(any());
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
  this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
  assertThat(this.service.getClass().getInterfaces())
    .contains(MethodSecurityService.class);
  assertThatThrownBy(() -> this.service.preAuthorize())
    .isInstanceOf(AccessDeniedException.class);
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to return a book by id for role 'USER'")
@Test
@WithMockUser
void verifyReturnByIdAccessIsGrantedForUser() {
 Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
 when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
 when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
 when(userRepository.findById(any(UUID.class))).thenReturn(
     Mono.just(new User(UUID.randomUUID(),"test@example.com", "secret", "Max",
         "Maier", Collections.singletonList(Role.USER))));
 StepVerifier.create(bookService.returnById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to create a user for role 'ADMIN'")
@Test
@WithMockUser(roles = "ADMIN")
void verifyCreateAccessIsGrantedForAdmin() {
 when(userRepository.insert(Mockito.<Mono<User>>any())).thenReturn(Flux.just(new User(UUID.randomUUID(),
     "test@example.com", "secret", "Max", "Maier",
     Collections.singletonList(Role.USER))));
 StepVerifier.create(userService.create(Mono.just(new UserResource(UUID.randomUUID(),
     "test@example.com", "secret", "Max", "Maier",
     Collections.singletonList(Role.USER))))).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to borrow a book by id for role 'USER'")
@Test
@WithMockUser
void verifyBorrowByIdAccessIsGrantedForUser() {
  Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
  when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
  when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
  when(userRepository.findById(any(UUID.class))).thenReturn(
      Mono.just(new User(UUID.randomUUID(), "test@example.com", "Max",
          "Maier", Collections.singletonList(Role.USER))));
  StepVerifier.create(bookService.borrowById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
  verify(bookRepository).save(any());
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
  this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class).autowire();
  assertThatThrownBy(() -> this.service.preAuthorize())
    .isInstanceOf(AccessDeniedException.class);
  assertThatThrownBy(() -> this.service.secured())
    .isInstanceOf(AccessDeniedException.class);
  assertThatThrownBy(() -> this.service.jsr250())
    .isInstanceOf(AccessDeniedException.class);
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to return a book by id for role 'USER'")
@Test
@WithMockUser(authorities = "SCOPE_user")
void verifyReturnByIdAccessIsGrantedForUser() {
  Book book = new Book(UUID.randomUUID(), "123456", "title", "description", Arrays.asList("author1", "author2"), false, null);
  when(bookRepository.findById(any(UUID.class))).thenReturn(Mono.just(book));
  when(bookRepository.save(any(Book.class))).thenReturn(Mono.just(book));
  when(userRepository.findById(any(UUID.class))).thenReturn(
      Mono.just(new User(UUID.randomUUID(), "test@example.com", "Max",
          "Maier", Collections.singletonList(Role.USER))));
  StepVerifier.create(bookService.returnById(UUID.randomUUID(), UUID.randomUUID())).verifyComplete();
}

代码示例来源:origin: andifalk/reactive-spring-security-5-workshop

@DisplayName("grants access to create a book for role 'CURATOR'")
@Test
@WithMockUser(roles = "CURATOR")
void verifyCreateAccessIsGrantedForCurator() {
 when(bookRepository.insert(Mockito.<Mono<Book>>any())).thenReturn(Flux.just(new Book()));
 StepVerifier.create(bookService.create(Mono.just(new BookResource(UUID.randomUUID(),
         "123456789", "title", "description", Collections.singletonList("author"),
         false, null)
     ))).verifyComplete();
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
  this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
  assertThatThrownBy(() -> this.service.preAuthorize())
    .isInstanceOf(AccessDeniedException.class);
  assertThatThrownBy(() -> this.service.secured())
    .isInstanceOf(AccessDeniedException.class);
}

相关文章