org.springframework.security.authentication.TestingAuthenticationToken Java Examples

The following examples show how to use org.springframework.security.authentication.TestingAuthenticationToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LogsearchExternalServerAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationNullUser() {
  expect(mockAuthPropsConfig.isAuthExternalEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken(null, "credentials");
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown BadCredentialsException", false);
  } catch(BadCredentialsException e) {
    assertEquals("Username can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #2
Source File: LogsearchSimpleAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationNullUser() {
  expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken(null, "credentials");
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown BadCredentialsException", false);
  } catch(BadCredentialsException e) {
    assertEquals("Username can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #3
Source File: JobServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteJobAssertNoErrorWhenUserHasPermissions() throws Exception
{
    // Start a job that will wait in a receive task
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH);
    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations()
        .add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.EXECUTE)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason"));
    }
    catch (AccessDeniedException e)
    {
        fail();
    }
}
 
Example #4
Source File: AccountTransactionViewIntegrationTest.java    From kid-bank with Apache License 2.0 6 votes vote down vote up
@Test
public void spendToNewAccountShouldHaveOneSpendTransaction() throws Exception {
  UserProfile parentProfile = new UserProfile("Parent Spender",
                                              new PhoneNumber("+15555555555"),
                                              "[email protected]",
                                              Role.PARENT);

  mockMvc.perform(post("/spend")
                      .with(authentication(
                          new TestingAuthenticationToken(parentProfile, null, "ROLE_PARENT")))
                      .param("date", "2018-12-19")
                      .param("amount", "49.95")
                      .param("description", "Video game"))
         .andExpect(redirectedUrl(AccountController.ACCOUNT_URL));

  Collection<TransactionView> transactions = transactionsFromModel();

  assertThat(transactions)
      .contains(new TransactionView(
          "12/19/2018", "Spend", "$49.95", "Video game", "Parent Spender"));
}
 
Example #5
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNotSecurityUserWrapper() throws Exception
{
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("streetcreds", null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
    }
}
 
Example #6
Source File: LogsearchSimpleAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationSuccessful() {
  expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  
  Authentication authenticationResult = provider.authenticate(authentication);
  assertEquals("principal", authenticationResult.getName());
  assertEquals("credentials", authenticationResult.getCredentials());
  assertEquals(1, authenticationResult.getAuthorities().size());
  assertEquals(new SimpleGrantedAuthority("ROLE_USER"), authenticationResult.getAuthorities().iterator().next());
  
  verify(mockAuthPropsConfig);
}
 
Example #7
Source File: WithOAuth2MockAccessTokenSecurityContextFactory.java    From microservices-basics-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Provide the mock user information to be used
 * 
 * @param withMockOAuth2Token
 * @return
 */
private Authentication getAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	User userPrincipal = new User(withMockOAuth2Token.userName(), withMockOAuth2Token.password(), true, true, true,
			true, authorities);

	HashMap<String, String> details = new HashMap<String, String>();
	details.put("user_name", withMockOAuth2Token.userName());
	details.put("email", "[email protected]");
	details.put("name", "Anil Allewar");

	TestingAuthenticationToken token = new TestingAuthenticationToken(userPrincipal, null, authorities);
	token.setAuthenticated(true);
	token.setDetails(details);

	return token;
}
 
Example #8
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the namespace security advice is enabled. Try calling a secured method with a mock user in the context with invalid permissions. The
 * expectation is that the method call fails with AccessDeniedException if the advice is enabled.
 */
@Test
public void assertAdviceEnabled()
{
    // put a fake user with no permissions into the security context
    // the security context is cleared on the after() method of this test suite
    String username = "username";
    Class<?> generatedByClass = getClass();
    ApplicationUser applicationUser = new ApplicationUser(generatedByClass);
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(Collections.emptySet());
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        businessObjectDefinitionServiceImpl
            .createBusinessObjectDefinition(new BusinessObjectDefinitionCreateRequest(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, null, null, null));
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
    }
}
 
Example #9
Source File: GatewayEventRestEndpointTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
  public void shouldRaiseExceptionInvalidJsonPub() throws Exception {
      SecurityContext context = SecurityContextHolder.getContext();
      Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null);
      context.setAuthentication(auth);

      when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883"))
      	.thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok()
      			.withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build());
      when(jsonParsingService.isValid("[{'a': 10}")).thenReturn(false);

getMockMvc().perform(
              post("/gateway/pub")
              	.flashAttr("principal", gateway)
                  .contentType(MediaType.APPLICATION_JSON)
                  .content("[{'a': 10}"))
              	.andExpect(status().isBadRequest())
              	.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"integration.rest.invalid.body\",\"message\":\"Event content is in invalid format. Expected to be a valid JSON string\"}")));

  }
 
Example #10
Source File: CfpControllerTest.java    From spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@WithMockUser("jsmith")
@Test
public void submitTalk() throws Exception {
	Authentication authentication = new TestingAuthenticationToken(
			new User("jsmith", "John Smith"), "secret", "ROLE_USER");

	given(this.submissionService.create(any())).willReturn(new Submission());
	this.mvc.perform(post("/submit")
			.param("title", "Alice in Wonderland")
			.param("summary", "my abstract")
			.param("track", Track.ALTERNATE_LANGUAGES.getId())
			.param("notes", "this rocks")
			.with(authentication(authentication))
			.with(csrf()))
			.andExpect(status().isFound())
			.andExpect(header().string(HttpHeaders.LOCATION, "/submit?navSection=submit"));
	verify(this.submissionService).create(any());
}
 
Example #11
Source File: JobServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetJobAssertAccessDeniedGivenJobRunningAndUserDoesNotHavePermissions() throws Exception
{
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH);
    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        jobService.getJob(job.getId(), false);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD),
            e.getMessage());
    }
}
 
Example #12
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception
{
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
    }
}
 
Example #13
Source File: JobServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetJobAssertNoErrorGivenJobRunningAndUserDoesHasPermissions() throws Exception
{
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH);
    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        jobService.getJob(job.getId(), false);
    }
    catch (AccessDeniedException e)
    {
        fail();
    }
}
 
Example #14
Source File: PinpointWebSocketTimerTaskDecoratorTest.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationPropagation() throws InterruptedException {
    final int numThreads = 3;
    final Authentication[] authentications = new Authentication[numThreads];
    for (int i = 0; i < authentications.length; i++) {
        final String principal = "principal" + i;
        final String credential = "credential" + i;
        authentications[i] = new TestingAuthenticationToken(principal, credential);
    }
    final CountDownLatch schedulerLatch = new CountDownLatch(numThreads);
    final Timer timer = new Timer();

    for (Authentication authentication : authentications) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SecurityContext securityContext = new SecurityContextImpl();
                securityContext.setAuthentication(authentication);
                SecurityContextHolder.setContext(securityContext);
                TimerTask timerTask = timerTaskDecoratorFactory.createTimerTaskDecorator().decorate(new TestTimerTask(schedulerLatch, authentication));
                timer.schedule(timerTask, DELAY_MS);
            }
        }).start();
    }
    Assert.assertTrue("Timed out waiting for timer task completion", schedulerLatch.await(2 * DELAY_MS, TimeUnit.MILLISECONDS));
}
 
Example #15
Source File: LogsearchAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Ignore("Until EasyMock 3.7 upgrade - waiting for release")
@Test
public void testOneExceptionNoOneAuthenticates() {
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  expect(mockFileProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);
  expect(mockExternalServerProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg1") {});
  expect(mockSimpleProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);
  
  replay(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown AuthenticationException", false);
  } catch(AuthenticationException e) {
    assertEquals(e.getMessage(), "msg1");
  }
  
  verify(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
}
 
Example #16
Source File: LogsearchAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Ignore("Until EasyMock 3.7 upgrade - waiting for release")
@Test
public void testTwoExceptionNoOneAuthenticates() {
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  expect(mockFileProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg1") {});
  expect(mockExternalServerProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg2") {});
  expect(mockSimpleProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);

  replay(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown AuthenticationException", false);
  } catch(AuthenticationException e) {
    assertEquals(e.getMessage(), "msg1");
  }
  
  verify(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
}
 
Example #17
Source File: LogsearchExternalServerAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationUnsuccessful() throws Exception {
  expect(mockAuthPropsConfig.isAuthExternalEnabled()).andReturn(true);
  expect(mockAuthPropsConfig.getExternalAuthLoginUrl()).andReturn("http://server.com?userName=$USERNAME");
  expect(mockAuthPropsConfig.getAllowedRoles()).andReturn(Arrays.asList("AMBARI.ADMINISTRATOR"));
  expect(mockExternalServerClient.sendGETRequest("http://server.com?userName=principal", String.class, "principal", "credentials"))
  .andReturn("{\"permission_name\": \"NOT.AMBARI.ADMINISTRATOR\" }");
  
  replay(mockAuthPropsConfig, mockExternalServerClient);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown BadCredentialsException", false);
  } catch (BadCredentialsException e) {
    assertEquals("Bad credentials", e.getMessage());
  }
  
  verify(mockAuthPropsConfig, mockExternalServerClient);
}
 
Example #18
Source File: LogsearchFileAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationEmptyPassword() {
  expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "");
  
  try {
    provider.authenticate(authentication);
    fail("Should have thrown BadCredentialsException");
  } catch(BadCredentialsException e) {
    assertEquals("Password can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #19
Source File: LogsearchFileAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationNullPassword() {
  expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken("principal", null);
  
  try {
    provider.authenticate(authentication);
    fail("Should have thrown BadCredentialsException");
  } catch(BadCredentialsException e) {
    assertEquals("Password can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #20
Source File: LogsearchFileAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationUnknownUser() {
  expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
  expect(mockUserDetailsService.loadUserByUsername("principal")).andReturn(null);
  
  replay(mockAuthPropsConfig, mockUserDetailsService);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  try {
    provider.authenticate(authentication);
    fail("Should have thrown BadCredentialsException");
  } catch (BadCredentialsException e) {
    assertEquals("User not found.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig, mockUserDetailsService);
}
 
Example #21
Source File: MongoClientTokenServicesTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@Test
public void shouldGetAccessToken() {
    //Given
    final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());

    //And
    final String authenticationId = string().next();
    given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);

    //And
    final OAuth2AccessToken expectedToken = oAuth2AccessTokenBuilder().build();
    given(mongoOAuth2ClientTokenRepository.findByAuthenticationId(authenticationId)).willReturn(mongoOAuth2ClientTokenBuilder().token(expectedToken).build());

    //When
    final OAuth2AccessToken accessToken = mongoClientTokenServices.getAccessToken(oAuth2ProtectedResourceDetails, authentication);

    //Then
    assertThat(accessToken).isEqualTo(expectedToken);
}
 
Example #22
Source File: LogsearchFileAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationNoPassword() {
  List<GrantedAuthority> grantedAuths = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
  User user = new User("principal", null, grantedAuths);
  
  expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
  expect(mockUserDetailsService.loadUserByUsername("principal")).andReturn(user);
  
  replay(mockAuthPropsConfig, mockUserDetailsService);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  try {
    provider.authenticate(authentication);
    fail("Should have thrown BadCredentialsException");
  } catch (BadCredentialsException e) {
    assertEquals("Password can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig, mockUserDetailsService);
}
 
Example #23
Source File: LogsearchSimpleAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationEmptyUser() {
  expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken("", "credentials");
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown BadCredentialsException", false);
  } catch(BadCredentialsException e) {
    assertEquals("Username can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #24
Source File: JobServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetJobAssertAccessDeniedGivenJobCompletedAndUserDoesNotHavePermissions() throws Exception
{
    jobDefinitionServiceTestHelper.createJobDefinition(null);
    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        jobService.getJob(job.getId(), false);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD),
            e.getMessage());
    }
}
 
Example #25
Source File: JobServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetJobAssertNoErrorGivenJobCompletedAndUserDoesHasPermissions() throws Exception
{
    jobDefinitionServiceTestHelper.createJobDefinition(null);
    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
            null));

    try
    {
        jobService.getJob(job.getId(), false);
    }
    catch (AccessDeniedException e)
    {
        fail();
    }
}
 
Example #26
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Test the case where user has the namespace but does not have the permission
 */
@Test
public void checkPermissionAssertAccessDeniedWhenCurrentUserHasWrongPermissionType() throws Exception
{
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has WRITE permissions, but the method requires READ
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.WRITE)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"", userId), e.getMessage());
    }
}
 
Example #27
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Test where a method is annotated with multiple NamespacePermission annotations. Asserts that the user will all permissions do not throw an exception.
 */
@Test
public void checkPermissionAssertNoExceptionWhenMultipleAnnotationsAndAllPermissionsValid() throws Exception
{
    // Mock a join point of the method call
    // mockMethodMultipleAnnotations("foo", "bar");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethodMultipleAnnotations", String.class, String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace1", "namespace2"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo", "bar"});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ)));
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("bar", Arrays.asList(NamespacePermissionEnum.WRITE)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    }
    catch (AccessDeniedException e)
    {
        fail();
    }
}
 
Example #28
Source File: SpringSecurityAuthenticationContextTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseAuthenticationFromSpringSecurityContext() {
    SecurityContext context = SecurityContextHolder.getContext();
    TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("test", null);
    context.setAuthentication(authenticationToken);

    assertThat(underTest.getAuthenticatedUserId())
        .as("Flowable authenticated userId")
        .isEqualTo("test");

    assertThat(underTest.getPrincipal())
        .as("Flowable authenticated principal")
        .isSameAs(authenticationToken);
}
 
Example #29
Source File: NamespaceSecurityHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void getAuthorizedNamespacesWhenNoApplicationUserInContextReturnEmpty()
{
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper("username", "", true, true, true, true, Collections.emptyList(), null), null));

    Set<String> authorizedNamespaces = namespaceSecurityHelper.getAuthorizedNamespaces(NamespacePermissionEnum.READ);
    assertEquals(0, authorizedNamespaces.size());
}
 
Example #30
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Test case where the current user has both the namespace and the appropriate permissions.
 */
@Test
public void checkPermissionAssertNoExceptionWhenHasPermissions() throws Exception
{
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    }
    catch (AccessDeniedException e)
    {
        fail();
    }
}