Search in sources :

Example 6 with AuthenticationToken

use of org.apache.shiro.authc.AuthenticationToken in project ddf by codice.

the class SecurityManagerImplTest method testAuthToken.

/**
     * Creates mock objects and uses those to pass through the system when an authentication token
     * is used.
     *
     * @throws SecurityServiceException
     */
@Test
public void testAuthToken() throws SecurityServiceException {
    // mock setup
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    SecurityToken secToken = new SecurityToken();
    principals.add(secToken, REALM_NAME);
    AuthenticationToken authToken = mock(AuthenticationToken.class);
    when(authToken.getCredentials()).thenReturn("testUser");
    AuthenticationInfo info = mock(AuthenticationInfo.class);
    when(info.getPrincipals()).thenReturn(principals);
    // realm
    Realm realm = mock(Realm.class);
    when(realm.getAuthenticationInfo(authToken)).thenReturn(info);
    when(realm.supports(authToken)).thenReturn(Boolean.TRUE);
    when(realm.getName()).thenReturn(REALM_NAME);
    SecurityManagerImpl manager = new SecurityManagerImpl();
    manager.setRealms(Arrays.asList(new Realm[] { realm }));
    Subject subject = manager.getSubject(authToken);
    assertNotNull(subject);
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) Realm(org.apache.shiro.realm.Realm) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) Subject(ddf.security.Subject) Test(org.junit.Test)

Example 7 with AuthenticationToken

use of org.apache.shiro.authc.AuthenticationToken in project ddf by codice.

the class TestWorkspaceQueryService method testRun.

@SuppressWarnings("unchecked")
@Test
public void testRun() throws SchedulerException, UnsupportedQueryException, SourceUnavailableException, FederationException {
    String workspaceId = "3";
    QueryUpdateSubscriber queryUpdateSubscriber = mock(QueryUpdateSubscriber.class);
    WorkspaceService workspaceService = mock(WorkspaceService.class);
    CatalogFramework catalogFramework = mock(CatalogFramework.class);
    FilterBuilder filterBuilder = mock(FilterBuilder.class);
    Scheduler scheduler = mock(Scheduler.class);
    when(scheduler.getContext()).thenReturn(mock(SchedulerContext.class));
    Supplier<Optional<Scheduler>> schedulerSupplier = () -> Optional.of(scheduler);
    SecurityService securityService = new SecurityService() {

        @Override
        public Subject getSystemSubject() {
            return mock(Subject.class);
        }

        @Override
        public Map<String, Serializable> addSystemSubject(Map<String, Serializable> properties) {
            return properties;
        }
    };
    FilterService filterService = mock(FilterService.class);
    when(filterService.getModifiedDateFilter(any())).thenReturn(mock(Filter.class));
    when(filterBuilder.anyOf(Mockito.any(Filter.class))).thenReturn(mock(Or.class));
    when(filterBuilder.allOf(Mockito.<Filter>anyVararg())).thenReturn(mock(And.class));
    WorkspaceQueryServiceImpl workspaceQueryServiceImpl = new WorkspaceQueryServiceImpl(queryUpdateSubscriber, workspaceService, catalogFramework, filterBuilder, schedulerSupplier, securityService, filterService);
    workspaceQueryServiceImpl.setQueryTimeInterval(60);
    String ecql = "area( Polygon((10 10, 20 10, 20 20, 10 10)) ) BETWEEN 10000 AND 30000";
    WorkspaceMetacardImpl workspaceMetacard = mock(WorkspaceMetacardImpl.class);
    when(workspaceMetacard.getId()).thenReturn(workspaceId);
    QueryMetacardImpl queryMetacardWithSource = mock(QueryMetacardImpl.class);
    when(queryMetacardWithSource.getSources()).thenReturn(Collections.singletonList("SomeSource"));
    when(queryMetacardWithSource.getCql()).thenReturn(ecql);
    Attribute id1 = mock(Attribute.class);
    when(id1.getValue()).thenReturn("1");
    when(queryMetacardWithSource.getAttribute(Metacard.ID)).thenReturn(id1);
    QueryMetacardImpl queryMetacardWithoutSource = mock(QueryMetacardImpl.class);
    when(queryMetacardWithoutSource.getSources()).thenReturn(Collections.emptyList());
    when(queryMetacardWithoutSource.getCql()).thenReturn(ecql);
    Attribute id2 = mock(Attribute.class);
    when(id2.getValue()).thenReturn("2");
    when(queryMetacardWithoutSource.getAttribute(Metacard.ID)).thenReturn(id2);
    Map<String, Pair<WorkspaceMetacardImpl, List<QueryMetacardImpl>>> queryMetacards = Collections.singletonMap(id2.getValue().toString(), new ImmutablePair<>(workspaceMetacard, Arrays.asList(queryMetacardWithSource, queryMetacardWithoutSource)));
    when(workspaceService.getQueryMetacards()).thenReturn(queryMetacards);
    long hitCount1 = 10;
    long hitCount2 = 20;
    QueryResponse queryResponse = mock(QueryResponse.class);
    when(queryResponse.getHits()).thenReturn(hitCount1).thenReturn(hitCount2);
    when(catalogFramework.query(any())).thenReturn(queryResponse);
    workspaceQueryServiceImpl.setSubject(new Subject() {

        @Override
        public boolean isGuest() {
            return false;
        }

        @Override
        public Object getPrincipal() {
            return null;
        }

        @Override
        public PrincipalCollection getPrincipals() {
            return null;
        }

        @Override
        public boolean isPermitted(String s) {
            return false;
        }

        @Override
        public boolean isPermitted(Permission permission) {
            return false;
        }

        @Override
        public boolean[] isPermitted(String... strings) {
            return new boolean[0];
        }

        @Override
        public boolean[] isPermitted(List<Permission> list) {
            return new boolean[0];
        }

        @Override
        public boolean isPermittedAll(String... strings) {
            return false;
        }

        @Override
        public boolean isPermittedAll(Collection<Permission> collection) {
            return false;
        }

        @Override
        public void checkPermission(String s) throws AuthorizationException {
        }

        @Override
        public void checkPermission(Permission permission) throws AuthorizationException {
        }

        @Override
        public void checkPermissions(String... strings) throws AuthorizationException {
        }

        @Override
        public void checkPermissions(Collection<Permission> collection) throws AuthorizationException {
        }

        @Override
        public boolean hasRole(String s) {
            return false;
        }

        @Override
        public boolean[] hasRoles(List<String> list) {
            return new boolean[0];
        }

        @Override
        public boolean hasAllRoles(Collection<String> collection) {
            return false;
        }

        @Override
        public void checkRole(String s) throws AuthorizationException {
        }

        @Override
        public void checkRoles(Collection<String> collection) throws AuthorizationException {
        }

        @Override
        public void checkRoles(String... strings) throws AuthorizationException {
        }

        @Override
        public void login(AuthenticationToken authenticationToken) throws AuthenticationException {
        }

        @Override
        public boolean isAuthenticated() {
            return false;
        }

        @Override
        public boolean isRemembered() {
            return false;
        }

        @Override
        public Session getSession() {
            return null;
        }

        @Override
        public Session getSession(boolean b) {
            return null;
        }

        @Override
        public void logout() {
        }

        @Override
        public <V> V execute(Callable<V> callable) throws ExecutionException {
            try {
                return callable.call();
            } catch (Exception e) {
                throw new ExecutionException(e);
            }
        }

        @Override
        public void execute(Runnable runnable) {
        }

        @Override
        public <V> Callable<V> associateWith(Callable<V> callable) {
            return null;
        }

        @Override
        public Runnable associateWith(Runnable runnable) {
            return null;
        }

        @Override
        public void runAs(PrincipalCollection principalCollection) throws NullPointerException, IllegalStateException {
        }

        @Override
        public boolean isRunAs() {
            return false;
        }

        @Override
        public PrincipalCollection getPreviousPrincipals() {
            return null;
        }

        @Override
        public PrincipalCollection releaseRunAs() {
            return null;
        }
    });
    workspaceQueryServiceImpl.setCronString("0 0 0 * * ?");
    workspaceQueryServiceImpl.setQueryTimeoutMinutes(5L);
    workspaceQueryServiceImpl.run();
    ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class);
    verify(queryUpdateSubscriber).notify(argumentCaptor.capture());
    Map queryUpdateSubscriberArgumentRaw = argumentCaptor.getValue();
    Map<String, Pair<WorkspaceMetacardImpl, Long>> queryUpdateSubscriberArgument = (Map<String, Pair<WorkspaceMetacardImpl, Long>>) queryUpdateSubscriberArgumentRaw;
    assertThat(queryUpdateSubscriberArgument.get(workspaceId).getRight(), is(hitCount1 + hitCount2));
}
Also used : Serializable(java.io.Serializable) Or(org.opengis.filter.Or) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthorizationException(org.apache.shiro.authz.AuthorizationException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) QueryMetacardImpl(org.codice.ddf.catalog.ui.metacard.workspace.QueryMetacardImpl) CatalogFramework(ddf.catalog.CatalogFramework) SchedulerContext(org.quartz.SchedulerContext) Permission(org.apache.shiro.authz.Permission) Optional(java.util.Optional) WorkspaceService(org.codice.ddf.catalog.ui.query.monitor.api.WorkspaceService) And(org.opengis.filter.And) QueryUpdateSubscriber(org.codice.ddf.catalog.ui.query.monitor.api.QueryUpdateSubscriber) Map(java.util.Map) Attribute(ddf.catalog.data.Attribute) Scheduler(org.quartz.Scheduler) FilterService(org.codice.ddf.catalog.ui.query.monitor.api.FilterService) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) Callable(java.util.concurrent.Callable) FilterBuilder(ddf.catalog.filter.FilterBuilder) SecurityService(org.codice.ddf.catalog.ui.query.monitor.api.SecurityService) ExecutionException(org.apache.shiro.subject.ExecutionException) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Subject(ddf.security.Subject) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) SchedulerException(org.quartz.SchedulerException) FederationException(ddf.catalog.federation.FederationException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) ExecutionException(org.apache.shiro.subject.ExecutionException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) Filter(org.opengis.filter.Filter) QueryResponse(ddf.catalog.operation.QueryResponse) WorkspaceMetacardImpl(org.codice.ddf.catalog.ui.metacard.workspace.WorkspaceMetacardImpl) Session(org.apache.shiro.session.Session) Test(org.junit.Test)

Example 8 with AuthenticationToken

use of org.apache.shiro.authc.AuthenticationToken in project killbill by killbill.

the class TenantFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    // Lookup tenant information in the headers
    String apiKey = null;
    String apiSecret = null;
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        apiKey = httpServletRequest.getHeader(JaxrsResource.HDR_API_KEY);
        apiSecret = httpServletRequest.getHeader(JaxrsResource.HDR_API_SECRET);
    }
    // Multi-tenancy is enabled if this filter is installed, we can't continue without credentials
    if (apiKey == null || apiSecret == null) {
        final String errorMessage = String.format("Make sure to set the %s and %s headers", JaxrsResource.HDR_API_KEY, JaxrsResource.HDR_API_SECRET);
        handleAuthenticationError(errorMessage, chain, request, response);
        return;
    }
    // Verify the apiKey/apiSecret combo
    final AuthenticationToken token = new UsernamePasswordToken(apiKey, apiSecret);
    try {
        modularRealmAuthenticator.authenticate(token);
    } catch (final AuthenticationException e) {
        final String errorMessage = e.getLocalizedMessage();
        handleAuthenticationError(errorMessage, chain, request, response);
        return;
    }
    try {
        // Load the tenant in the request object (apiKey is unique across tenants)
        final Tenant tenant = tenantUserApi.getTenantByApiKey(apiKey);
        request.setAttribute(TENANT, tenant);
        // Create a dummy context, to set the MDC very early for LoggingFilter
        context.createContext(request);
        chain.doFilter(request, response);
    } catch (final TenantApiException e) {
        // Should never happen since Shiro validated the credentials?
        log.error("Couldn't find the tenant? - should never happen!", e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Tenant(org.killbill.billing.tenant.api.Tenant) AuthenticationException(org.apache.shiro.authc.AuthenticationException) TenantApiException(org.killbill.billing.tenant.api.TenantApiException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 9 with AuthenticationToken

use of org.apache.shiro.authc.AuthenticationToken in project killbill by killbill.

the class TestDefaultTenantDao method testWeCanStoreAndMatchCredentials.

@Test(groups = "slow")
public void testWeCanStoreAndMatchCredentials() throws Exception {
    final DefaultTenant tenant = new DefaultTenant(UUID.randomUUID(), null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
    tenantDao.create(new TenantModelDao(tenant), internalCallContext);
    // Verify we can retrieve it
    Assert.assertEquals(tenantDao.getTenantByApiKey(tenant.getApiKey()).getId(), tenant.getId());
    // Verify we can authenticate against it
    final AuthenticationInfo authenticationInfo = tenantDao.getAuthenticationInfoForTenant(tenant.getId());
    // Good combo
    final AuthenticationToken goodToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret());
    Assert.assertTrue(KillbillCredentialsMatcher.getCredentialsMatcher(securityConfig).doCredentialsMatch(goodToken, authenticationInfo));
    // Bad combo
    final AuthenticationToken badToken = new UsernamePasswordToken(tenant.getApiKey(), tenant.getApiSecret() + "T");
    Assert.assertFalse(KillbillCredentialsMatcher.getCredentialsMatcher(securityConfig).doCredentialsMatch(badToken, authenticationInfo));
}
Also used : DefaultTenant(org.killbill.billing.tenant.api.DefaultTenant) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.testng.annotations.Test)

Example 10 with AuthenticationToken

use of org.apache.shiro.authc.AuthenticationToken in project ddf by codice.

the class SecurityManagerImplTest method testAuthTokenNoRealm.

/**
     * Test to check for failure when no realms are added.
     *
     * @throws SecurityServiceException
     */
@Test
public void testAuthTokenNoRealm() throws SecurityServiceException {
    thrown.expect(org.apache.shiro.authc.AuthenticationException.class);
    thrown.expectMessage("Authentication failed for token submission");
    AuthenticationToken token = mock(AuthenticationToken.class);
    when(token.getCredentials()).thenReturn("testUser");
    AuthenticationInfo info = mock(AuthenticationInfo.class);
    Realm realm = mock(Realm.class);
    when(realm.getAuthenticationInfo(token)).thenReturn(info);
    SecurityManagerImpl manager = new SecurityManagerImpl();
    manager.getSubject(token);
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Realm(org.apache.shiro.realm.Realm) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo) Test(org.junit.Test)

Aggregations

AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)13 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)7 Test (org.junit.Test)6 AuthenticationException (org.apache.shiro.authc.AuthenticationException)4 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)4 Test (org.testng.annotations.Test)4 Subject (org.apache.shiro.subject.Subject)3 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)3 Subject (ddf.security.Subject)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)2 AuthorizationException (org.apache.shiro.authz.AuthorizationException)2 Realm (org.apache.shiro.realm.Realm)2 BSTAuthenticationToken (org.codice.ddf.security.handler.api.BSTAuthenticationToken)2 BaseAuthenticationToken (org.codice.ddf.security.handler.api.BaseAuthenticationToken)2 SAMLAuthenticationToken (org.codice.ddf.security.handler.api.SAMLAuthenticationToken)2 CatalogFramework (ddf.catalog.CatalogFramework)1 Attribute (ddf.catalog.data.Attribute)1 FederationException (ddf.catalog.federation.FederationException)1 FilterBuilder (ddf.catalog.filter.FilterBuilder)1