当前位置: 首页>>代码示例>>Java>>正文


Java TestingAuthenticationToken类代码示例

本文整理汇总了Java中org.springframework.security.authentication.TestingAuthenticationToken的典型用法代码示例。如果您正苦于以下问题:Java TestingAuthenticationToken类的具体用法?Java TestingAuthenticationToken怎么用?Java TestingAuthenticationToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TestingAuthenticationToken类属于org.springframework.security.authentication包,在下文中一共展示了TestingAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setup

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@Before
public void setup() {
	resource = new ResourceOwnerPasswordResourceDetails();

	resource.setAccessTokenUri(serverRunning.getUrl("/sparklr2/oauth/token"));
	resource.setClientId("my-trusted-client");
	resource.setId("sparklr");
	resource.setScope(Arrays.asList("trust"));
	resource.setUsername("marissa");
	resource.setPassword("koala");

	OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
	existingToken = template.getAccessToken();
	((DefaultOAuth2AccessToken) existingToken).setExpiration(new Date(0L));

	SecurityContextImpl securityContext = new SecurityContextImpl();
	securityContext.setAuthentication(new TestingAuthenticationToken("marissa", "koala", "ROLE_USER"));
	SecurityContextHolder.setContext(securityContext);

}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:21,代码来源:RefreshTokenGrantTests.java

示例2: getAuthentication

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:anilallewar,项目名称:microservices-basics-spring-boot,代码行数:24,代码来源:WithOAuth2MockAccessTokenSecurityContextFactory.java

示例3: shouldRefuseRequestFromKonkerPlataform

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@Test
  public void shouldRefuseRequestFromKonkerPlataform() 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(json)).thenReturn(true);

getMockMvc().perform(
              post("/gateway/pub")
              	.flashAttr("principal", gateway)
              	.header("X-Konker-Version", "0.1")
                  .contentType(MediaType.APPLICATION_JSON)
                  .content(json))
              	.andExpect(status().isForbidden())
              	.andExpect(content().string(org.hamcrest.Matchers.containsString("origin")));

  }
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:22,代码来源:GatewayEventRestEndpointTest.java

示例4: shouldRaiseExceptionInvalidJsonPub

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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\"}")));

  }
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:21,代码来源:GatewayEventRestEndpointTest.java

示例5: shouldPubToKonkerPlataform

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@Test
  public void shouldPubToKonkerPlataform() 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(json)).thenReturn(true);

getMockMvc().perform(
              post("/gateway/pub")
              	.flashAttr("principal", gateway)
                  .contentType(MediaType.APPLICATION_JSON)
                  .content(json))
              	.andExpect(status().isOk())
              	.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"200\",\"message\":\"OK\"}")));

  }
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:21,代码来源:GatewayEventRestEndpointTest.java

示例6: main

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
public static void main(String[] args) {
    String user = null;
    if (args != null && args.length > 0) {
        user = args[0];
    }

    if (user == null || user.isEmpty()) {
        user = "rod";
    }

    // create the provider and initialize it with the 'configure' method
    LdapAuthorizationsProvider provider = new LdapAuthorizationsProvider();
    provider.configure(new HashMap<String, Serializable>());

    // set dummy authentication token corresponding to user 'rod'
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(user, null));

    System.out.println("Checking auths from LDAP for user '" + user + "'");

    // get the authorizations - this will connect to ldap using the values in geomesa-ldap.properties
    List<String> auths = provider.getAuthorizations();

    System.out.println("Retrieved auths: " + auths);
}
 
开发者ID:geomesa,项目名称:geomesa-tutorials,代码行数:25,代码来源:LdapAuthorizationsProviderTest.java

示例7: assertAdviceEnabled

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
/**
 * 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());
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:30,代码来源:NamespaceSecurityAdviceTest.java

示例8: checkPermissionAssertAccessDeniedWhenPrincipalIsNotSecurityUserWrapper

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:27,代码来源:NamespaceSecurityAdviceTest.java

示例9: checkPermissionAssertAccessDeniedWhenPrincipalIsNull

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:27,代码来源:NamespaceSecurityAdviceTest.java

示例10: testDeleteJobAssertNoErrorWhenUserHasPermissions

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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();
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:27,代码来源:JobServiceTest.java

示例11: testGetJobAssertAccessDeniedGivenJobCompletedAndUserDoesNotHavePermissions

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:27,代码来源:JobServiceTest.java

示例12: testGetJobAssertNoErrorGivenJobCompletedAndUserDoesHasPermissions

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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();
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:25,代码来源:JobServiceTest.java

示例13: testGetJobAssertAccessDeniedGivenJobRunningAndUserDoesNotHavePermissions

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:27,代码来源:JobServiceTest.java

示例14: testGetJobAssertNoErrorGivenJobRunningAndUserDoesHasPermissions

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@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();
    }
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:25,代码来源:JobServiceTest.java

示例15: setUp

import org.springframework.security.authentication.TestingAuthenticationToken; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
    reset(violationServiceMock, mockTeamOperations, mockViolationConverter);

    violationRequest = new Violation();
    violationRequest.setAccountId(ACCOUNT_ID);
    violationRequest.setRegion(REGION);
    violationRequest.setEventId(UUID.randomUUID().toString());

    violationResult = INITIALIZER.create(violation().id(0L).version(0L));

    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test-user", null));

    mockMvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build();
    objectMapper = new ObjectMapper();

    when(mockViolationConverter.convert(any(ViolationEntity.class))).thenAnswer(invocationOnMock -> {
        final ViolationEntity entity = (ViolationEntity) invocationOnMock.getArguments()[0];
        final Violation dto = new Violation();
        dto.setId(entity.getId());
        return dto;
    });
}
 
开发者ID:zalando-stups,项目名称:fullstop,代码行数:24,代码来源:ViolationsControllerTest.java


注:本文中的org.springframework.security.authentication.TestingAuthenticationToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。