@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);
}
java类org.springframework.security.authentication.TestingAuthenticationToken的实例源码
RefreshTokenGrantTests.java 文件源码
项目:oauth-client-master
阅读 28
收藏 0
点赞 0
评论 0
GatewayEventRestEndpointTest.java 文件源码
项目:konker-platform
阅读 25
收藏 0
点赞 0
评论 0
@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")));
}
GatewayEventRestEndpointTest.java 文件源码
项目:konker-platform
阅读 24
收藏 0
点赞 0
评论 0
@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\"}")));
}
GatewayEventRestEndpointTest.java 文件源码
项目:konker-platform
阅读 20
收藏 0
点赞 0
评论 0
@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\"}")));
}
LdapAuthorizationsProviderTest.java 文件源码
项目:geomesa-tutorials
阅读 25
收藏 0
点赞 0
评论 0
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);
}
NamespaceSecurityAdviceTest.java 文件源码
项目:herd
阅读 22
收藏 0
点赞 0
评论 0
/**
* 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());
}
}
NamespaceSecurityAdviceTest.java 文件源码
项目:herd
阅读 23
收藏 0
点赞 0
评论 0
@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());
}
}
NamespaceSecurityAdviceTest.java 文件源码
项目:herd
阅读 22
收藏 0
点赞 0
评论 0
@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());
}
}
JobServiceTest.java 文件源码
项目:herd
阅读 26
收藏 0
点赞 0
评论 0
@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();
}
}
JobServiceTest.java 文件源码
项目:herd
阅读 27
收藏 0
点赞 0
评论 0
@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());
}
}
JobServiceTest.java 文件源码
项目:herd
阅读 24
收藏 0
点赞 0
评论 0
@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();
}
}
JobServiceTest.java 文件源码
项目:herd
阅读 28
收藏 0
点赞 0
评论 0
@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());
}
}
JobServiceTest.java 文件源码
项目:herd
阅读 26
收藏 0
点赞 0
评论 0
@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();
}
}
ViolationsControllerTest.java 文件源码
项目:fullstop
阅读 21
收藏 0
点赞 0
评论 0
@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;
});
}
ShibbolethPreAuthenticatedProcessingFilterTest.java 文件源码
项目:OpenConext-pdp
阅读 25
收藏 0
点赞 0
评论 0
@Test
public void principalChanged() {
MockHttpServletRequest request = new MockHttpServletRequest();
assertFalse(filter.principalChanged(request,
new TestingAuthenticationToken(new FederatedUser(
"uid", "mock-idp", "John Doe", emptySet(), emptySet(),
AuthorityUtils.createAuthorityList("USER")), "N/A")
)
);
assertTrue(filter.principalChanged(request,
new TestingAuthenticationToken(new RunAsFederatedUser(
"uid", "mock-idp", "John Doe", emptySet(), emptySet(),
AuthorityUtils.createAuthorityList("USER")), "N/A")
)
);
request.addHeader(X_IMPERSONATE, true);
assertTrue(filter.principalChanged(request, null));
}
DefaultAuthorizationServiceTest.java 文件源码
项目:lognavigator
阅读 19
收藏 0
点赞 0
评论 0
@Test
public void testGetAuthorizedLogAccessConfigs() throws Exception {
// given
Set<LogAccessConfig> allLogAccessConfigs = new HashSet<LogAccessConfig>();
LogAccessConfig logAccessConfig = new LogAccessConfig("log-with-onerole-authorized", LogAccessType.LOCAL, "localhost", "/log");
logAccessConfig.setAuthorizedRoles(Arrays.asList("onerole"));
allLogAccessConfigs.add(logAccessConfig);
logAccessConfig = new LogAccessConfig("log-with-oneuser-authorized", LogAccessType.LOCAL, "localhost", "/log");
logAccessConfig.setAuthorizedUsers(Arrays.asList("oneuser"));
allLogAccessConfigs.add(logAccessConfig);
TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "onerole");
// when
Set<LogAccessConfig> authorizedLogAccessConfigs = authorizationService.getAuthorizedLogAccessConfigs(allLogAccessConfigs, authenticatedUser);
// then
assertEquals(1, authorizedLogAccessConfigs.size());
assertEquals("log-with-onerole-authorized", authorizedLogAccessConfigs.iterator().next().getId());
}
MongodbMutableAclServiceTest.java 文件源码
项目:spring-security-acl-mongodb
阅读 24
收藏 0
点赞 0
评论 0
@Test
public void cumulativePermissions() {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, "110");
MutableAcl topParent = mongodbMutableAclService.createAcl(topParentOid);
// Add an ACE permission entry
Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION);
assertEquals(17, cm.getMask());
Sid benSid = new PrincipalSid(auth);
topParent.insertAce(0, cm, benSid, true);
assertEquals(1, topParent.getEntries().size());
// Explicitly save the changed ACL
topParent = mongodbMutableAclService.updateAcl(topParent);
// Check the mask was retrieved correctly
assertEquals(17, topParent.getEntries().get(0).getPermission().getMask());
assertTrue(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true));
SecurityContextHolder.clearContext();
}
WorkflowServiceTestCase.java 文件源码
项目:openeos
阅读 26
收藏 0
点赞 0
评论 0
@Test
public void testAutoAddUserParameter() {
WorkflowEngine engine = mock(WorkflowEngine.class);
ServiceRegistration<WorkflowEngine> registration = bc.registerService(WorkflowEngine.class, engine, null);
URL test1 = getClass().getClassLoader().getResource(TEST1_FILE);
Deployment deploy1 = workflowService.createDeployment().key("testAutoAddUserParameter").addURL(test1)
.enableDuplicateFiltering().deploy();
WorkflowDefinition def = workflowService.getLastWorkflowDefinitionByKey(TEST1_KEY);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("testUser", "testCredentials"));
workflowService.startProcess(def.getId());
ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
verify(engine).startProcess(eq(def.getId()), captor.capture());
Map<String, Object> parameters = captor.getValue();
assertEquals("testUser", parameters.get(org.openeos.wf.Constants.LANUCHER_USER_PARAMETER));
registration.unregister();
workflowService.revertDeployment(deploy1.getId());
SecurityContextHolder.getContext().setAuthentication(null);
}
DashboardControllerIT.java 文件源码
项目:cf-sample-service
阅读 19
收藏 0
点赞 0
评论 0
@Test
public void home() throws Exception {
final Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
try {
final String userFullName = "John Smith";
final TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "cred");
authentication.setDetails(new DashboardAuthenticationDetails(new MockHttpServletRequest(), true, userFullName));
SecurityContextHolder.getContext().setAuthentication(authentication);
final MvcResult mvcResult = mvc
.perform(
request(HttpMethod.GET, "/dashboard/")
)
.andExpect(status().is(HttpStatus.OK.value()))
.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
.andReturn();
assertEquals(userFullName, mvcResult.getModelAndView().getModelMap().get(DashboardController.USER_FULL_NAME));
assertEquals(DashboardController.HOME_VIEW, mvcResult.getModelAndView().getViewName());
} finally {
SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
}
}
MongoClientTokenServicesTest.java 文件源码
项目:spring-security-mongo
阅读 29
收藏 0
点赞 0
评论 0
@Test
public void shouldSaveAccessToken() {
//Given
final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());
final OAuth2AccessToken oAuth2AccessToken = oAuth2AccessTokenBuilder().build();
//And
final String authenticationId = string().next();
given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);
//When
mongoClientTokenServices.saveAccessToken(oAuth2ProtectedResourceDetails, authentication, oAuth2AccessToken);
//Then
verify(keyGenerator, atLeastOnce()).extractKey(oAuth2ProtectedResourceDetails, authentication);
verify(mongoOAuth2ClientTokenRepository).save(any(MongoOAuth2ClientToken.class));
verify(mongoOAuth2ClientTokenRepository).deleteByAuthenticationId(authenticationId);
}
MongoClientTokenServicesTest.java 文件源码
项目:spring-security-mongo
阅读 20
收藏 0
点赞 0
评论 0
@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);
}
Neo4jMutableAclServiceTest.java 文件源码
项目:spring-security-acl-neo4j
阅读 27
收藏 0
点赞 0
评论 0
@Test
@Rollback(false)
@Transactional(rollbackFor = Exception.class)
public void test2UpdateAcl() {
Authentication auth = new TestingAuthenticationToken("shazin", "N/A");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity oid = new ObjectIdentityImpl("my.test.Class", 1l);
MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid);
acl.insertAce(0, BasePermission.CREATE, new GrantedAuthoritySid(
"ROLE_USER"), true);
acl.insertAce(1, BasePermission.DELETE, new GrantedAuthoritySid(
"ROLE_ADMIN"), true);
mutableAclService.updateAcl(acl);
}
Neo4jMutableAclServiceTest.java 文件源码
项目:spring-security-acl-neo4j
阅读 21
收藏 0
点赞 0
评论 0
@Test(expected = NotFoundException.class)
@Rollback(false)
@Transactional(rollbackFor = Exception.class)
public void test3DeleteAcl() {
Authentication auth = new TestingAuthenticationToken("shazin", "N/A");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity oid = new ObjectIdentityImpl("my.test.Class", 1l);
MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid);
assertEquals(acl.getEntries().size(), 2);
for (AccessControlEntry ace : acl.getEntries()) {
assertEquals(ace.getAcl().getObjectIdentity(), oid);
}
mutableAclService.deleteAcl(oid, true);
mutableAclService.readAclById(oid);
}
Neo4jAclServiceTest.java 文件源码
项目:spring-security-acl-neo4j
阅读 23
收藏 0
点赞 0
评论 0
@Test
@Rollback(false)
@Transactional(rollbackFor = Exception.class)
public void test4readAclById() {
Authentication auth = new TestingAuthenticationToken("shazin", "N/A");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
List<Sid> sids = Arrays.<Sid> asList(new PrincipalSid("USER_0"),
new GrantedAuthoritySid("ROLE_1"));
long start = System.nanoTime();
Acl acl = mutableAclService.readAclById(new ObjectIdentityImpl(
"com.test.Shazin1", 1l), sids);
long end = System.nanoTime();
System.out.println("Reading 1 objects in " + (end - start));
assertNotNull(acl);
assertEquals(2, acl.getEntries().size());
}
EntityTypeRepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 24
收藏 0
点赞 0
评论 0
@Test
public void addWithKnownBackend()
{
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("anonymous", null, "ROLE_SU"));
EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock();
when(entityType.getAttributes()).thenReturn(emptyList());
String backendName = "knownBackend";
when(entityType.getBackend()).thenReturn(backendName);
MetaDataService metaDataService = mock(MetaDataService.class);
RepositoryCollection repoCollection = mock(RepositoryCollection.class);
when(metaDataService.getBackend(entityType)).thenReturn(repoCollection);
when(dataService.getMeta()).thenReturn(metaDataService);
repo.add(entityType);
verify(delegateRepository).add(entityType);
}
RepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 20
收藏 0
点赞 0
评论 0
@Test(expectedExceptions = MolgenisDataAccessException.class)
public void addStreamNoPermission()
{
TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null,
"ROLE_ENTITY_READ_" + entityId);
authentication.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(authentication);
Stream<Entity> entities = Stream.empty();
try
{
repositorySecurityDecorator.add(entities);
}
catch (MolgenisDataAccessException e)
{
verify(delegateRepository, times(1)).getEntityType();
verifyNoMoreInteractions(delegateRepository);
throw e;
}
}
RepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 21
收藏 0
点赞 0
评论 0
@Test
public void findAllPermission()
{
TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null,
"ROLE_ENTITY_READ_" + entityId);
authentication.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(authentication);
Stream<Object> ids = Stream.of(0, 1);
Fetch fetch = new Fetch();
Entity entity0 = mock(Entity.class);
Entity entity1 = mock(Entity.class);
Stream<Entity> entities = Stream.of(entity0, entity1);
when(delegateRepository.findAll(ids, fetch)).thenReturn(Stream.of(entity0, entity1));
assertEquals(entities.collect(toList()), repositorySecurityDecorator.findAll(ids, fetch).collect(toList()));
verify(delegateRepository, times(1)).findAll(ids, fetch);
}
RepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 25
收藏 0
点赞 0
评论 0
@Test(expectedExceptions = MolgenisDataAccessException.class)
public void deleteStreamNoPermission()
{
TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null,
"ROLE_ENTITY_READ_" + entityId);
authentication.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(authentication);
Stream<Entity> entities = Stream.empty();
try
{
repositorySecurityDecorator.delete(entities);
}
catch (MolgenisDataAccessException e)
{
verify(delegateRepository, times(1)).getEntityType();
verifyNoMoreInteractions(delegateRepository);
throw e;
}
}
RepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 19
收藏 0
点赞 0
评论 0
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void updateStream()
{
TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null,
"ROLE_ENTITY_WRITE_" + entityId);
authentication.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(authentication);
Entity entity0 = mock(Entity.class);
Stream<Entity> entities = Stream.of(entity0);
ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass(Stream.class);
doNothing().when(delegateRepository).update(captor.capture());
repositorySecurityDecorator.update(entities);
assertEquals(captor.getValue().collect(Collectors.toList()), singletonList(entity0));
}
RepositorySecurityDecoratorTest.java 文件源码
项目:molgenis
阅读 26
收藏 0
点赞 0
评论 0
@Test(expectedExceptions = MolgenisDataAccessException.class)
public void updateStreamNoPermission()
{
TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null,
"ROLE_ENTITY_READ_" + entityId);
authentication.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(authentication);
Stream<Entity> entities = Stream.empty();
try
{
repositorySecurityDecorator.update(entities);
}
catch (MolgenisDataAccessException e)
{
verify(delegateRepository, times(1)).getEntityType();
verifyNoMoreInteractions(delegateRepository);
throw e;
}
}