Example usage for org.apache.shiro.util ThreadContext bind

List of usage examples for org.apache.shiro.util ThreadContext bind

Introduction

In this page you can find the example usage for org.apache.shiro.util ThreadContext bind.

Prototype

public static void bind(Subject subject) 

Source Link

Document

Convenience method that simplifies binding a Subject to the ThreadContext.

Usage

From source file:br.com.criativasoft.opendevice.wsrest.filter.NewShiroInterceptor.java

License:Open Source License

@Override
public Action inspect(AtmosphereResource r) {

    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;

    String pathInfo = r.getRequest().getPathInfo();

    // Ignore Web Resources.
    if (WebUtils.isWebResource(pathInfo)) {
        return Action.CONTINUE;
    }/*from   w ww  .j av  a2 s. c  om*/

    if (r.getRequest().localAttributes().containsKey(FrameworkConfig.SECURITY_SUBJECT) == false) {
        try {

            // Create/find Subject using Request (and cookies) to restore state/session
            Subject currentUser = new CookieBuilder(r.getRequest(), r.getResponse()).buildWebSubject();
            ThreadContext.bind(currentUser);

            // Store to use in WebSocket / Broadcast response.
            r.getRequest().setAttribute(FrameworkConfig.SECURITY_SUBJECT, currentUser);

        } catch (UnavailableSecurityManagerException ex) {
            logger.info("Shiro Web Security : {}", ex.getMessage());
        } catch (java.lang.IllegalStateException ex) {
            logger.info("Shiro Web Environment : {}", ex.getMessage());
        }
    }

    return Action.CONTINUE;
}

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

License:Apache License

/**
 * It first looks the shiro subject in AccessControlContext since JMX will
 * use multiple threads to process operations from the same client, then it
 * looks into Shiro's thead context./*from   w  w  w  . j a v  a 2 s  . c om*/
 *
 * @return the shiro subject, null if security is not enabled
 */
public static Subject getSubject() {
    if (!isIntegratedSecurity) {
        return null;
    }

    Subject currentUser = null;

    // First try get the principal out of AccessControlContext instead of Shiro's Thread context
    // since threads can be shared between JMX clients.
    javax.security.auth.Subject jmxSubject = javax.security.auth.Subject
            .getSubject(AccessController.getContext());

    if (jmxSubject != null) {
        Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
        if (principals.size() > 0) {
            ShiroPrincipal principal = principals.iterator().next();
            currentUser = principal.getSubject();
            ThreadContext.bind(currentUser);
            return currentUser;
        }
    }

    // in other cases like admin rest call or pulse authorization
    currentUser = SecurityUtils.getSubject();

    if (currentUser == null || currentUser.getPrincipal() == null) {
        throw new GemFireSecurityException("Error: Anonymous User");
    }

    return currentUser;
}

From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java

License:Open Source License

@Override
public String login(Credential credential) throws ServiceException {
    String login = credential.getUsername();
    char[] password = credential.getPassword();
    boolean rememberMe = credential.isRememberMe();
    try {/*from w w  w.  j a v a2  s.  c o  m*/
        if (log.isTraceEnabled()) {
            log.trace(String.format("login - %s", credential));
        }
        UsernamePasswordToken token = new UsernamePasswordToken(login, password, rememberMe);
        AuthenticationInfo info = securityManager.authenticate(token);
        if (log.isTraceEnabled()) {
            if (info instanceof SimpleAuthenticationInfo) {
                PrincipalCollection principals = ((SimpleAuthenticationInfo) info).getPrincipals();
                for (Object principal : principals.asList()) {
                    log.trace("Principal: " + principal);
                }
            }
        }
        token.clear();
        // Create subject for the current principal
        Subject subject = new Subject.Builder().principals(info.getPrincipals()).buildSubject();
        // log.trace("subject.getPrincipal(): " + subject.getPrincipal());
        // Create session
        org.apache.shiro.session.Session session = subject.getSession(true);
        if (session == null) {
            throw new ServiceException(String.format("Unable to create session for ", login));
        }
        session.setAttribute(ES_DMS_LOGIN_ATTRIBUTE, login);
        session.setAttribute(ES_DMS_ID_ATTRIBUTE, ((User) subject.getPrincipal()).getId());
        ThreadContext.bind(subject);
        // if (log.isTraceEnabled()) {
        // Subject currentUser = SecurityUtils.getSubject();
        // log.trace("currentUser.getPrincipal(): " +
        // currentUser.getPrincipal());
        // }
        return session.getId().toString();
    } catch (AuthenticationException aEx) {
        String message = String.format("Authentication failed for %s", login);
        log.error(message, aEx);
        throw new ServiceException(message);
    }
}

From source file:com.github.richardwilly98.esdms.shiro.EsAuthenticationFilter.java

License:Open Source License

private Subject getSubjectFromSessionId(String token) throws ServiceException {
    if (log.isTraceEnabled()) {
        log.trace(String.format("Start getSubjectFromSessionId - %s", token));
    }//from  w ww  .  ja v a  2  s . c o m
    PrincipalCollection principals = getPrincipals(token);
    if (principals == null) {
        return null;
    }
    Subject subject = getSubjectByPrincipal(token, principals);
    if (subject != null) {
        // log.debug("Subject principal: " + subject.getPrincipal() +
        // " - authenticated: " + subject.isAuthenticated());
        ThreadContext.bind(subject);
    }
    return subject;
}

From source file:com.github.sdorra.shiro.ShiroRule.java

License:Open Source License

/**
 * Set a subject manually for the current method execution.
 *
 *
 * @param subject subject to set
 */
public void setSubject(Subject subject) {
    ThreadContext.bind(subject);
}

From source file:com.lcw.one.login.security.OneFormAuthenticationFilter.java

License:Open Source License

protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
    // TODO ??Spring Boot?WebSubject
    WebSubject.Builder builder = new WebSubject.Builder(request, response);
    WebSubject webSubject = builder.buildWebSubject();
    ThreadContext.bind(webSubject);

    String username = getUsername(request);
    String password = getPassword(request);
    if (password == null) {
        password = "";
    }//from  w w w .  j  a  v a2 s  .  co  m
    boolean rememberMe = isRememberMe(request);
    String host = getHost(request);
    String captcha = getCaptcha(request);
    return new OneUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha);
}

From source file:com.lcw.one.modules.sys.security.FormAuthenticationFilter.java

License:Open Source License

protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
    // TODO ??Spring Boot?WebSubject
    WebSubject.Builder builder = new WebSubject.Builder(request, response);
    WebSubject webSubject = builder.buildWebSubject();
    ThreadContext.bind(webSubject);

    String username = getUsername(request);
    String password = getPassword(request);
    if (password == null) {
        password = "";
    }/*w w  w.  jav  a 2  s . c om*/
    boolean rememberMe = isRememberMe(request);
    String host = getHost(request);
    String captcha = getCaptcha(request);
    return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha);
}

From source file:ddf.catalog.event.retrievestatus.AbstractDownloadsStatusEventPublisherTest.java

License:Open Source License

private void addSecurity() {
    org.apache.shiro.mgt.SecurityManager secManager = new DefaultSecurityManager();
    PrincipalCollection principals = new SimplePrincipalCollection(USER_ID, "testrealm");
    Subject subject = new Subject.Builder(secManager).principals(principals).session(new SimpleSession())
            .authenticated(true).buildSubject();
    ThreadContext.bind(secManager);
    ThreadContext.bind(subject);/*  www. ja  v  a  2s. c  om*/
}

From source file:ddf.catalog.impl.CatalogFrameworkImplTest.java

License:Open Source License

@Before
public void setup() throws StopProcessingException, PluginExecutionException, URISyntaxException,
        FederationException, IOException, CatalogTransformerException, InterruptedException {
    System.setProperty("bad.files",
            "crossdomain.xml,clientaccesspolicy.xml,.htaccess,.htpasswd,hosts,passwd,group,resolv.conf,nfs.conf,ftpd.conf,ntp.conf,web.config,robots.txt");
    System.setProperty("bad.file.extensions",
            ".exe,.jsp,.html,.js,.php,.phtml,.php3,.php4,.php5,.phps,.shtml,.jhtml,.pl,.py,.cgi,.msi,.com,.scr,.gadget,.application,.pif,.hta,.cpl,.msc,.jar,.kar,.bat,.cmd,.vb,.vbs,.vbe,.jse,.ws,.wsf,.wsc,.wsh,.ps1,.ps1xml,.ps2,.ps2xml,.psc1,.psc2,.msh,.msh1,.msh2,.mshxml,.msh1xml,.msh2xml,.scf,.lnk,.inf,.reg,.dll,.vxd,.cpl,.cfg,.config,.crt,.cert,.pem,.jks,.p12,.p7b,.key,.der,.csr,.jsb,.mhtml,.mht,.xhtml,.xht");
    System.setProperty("bad.mime.types",
            "text/html,text/javascript,text/x-javascript,application/x-shellscript,text/scriptlet,application/x-msdownload,application/x-msmetafile");
    System.setProperty("ignore.files", ".DS_Store,Thumbs.db");

    // Setup//from   ww  w .  j  a  va 2  s. co  m
    /*
     * Prepare to capture the ResourceResponse argument passed into
     * PostResourcePlugin.process(). We will verify that it contains a non-null ResourceRequest
     * in the verification section of this test.
     */
    argument = ArgumentCaptor.forClass(ResourceResponse.class);

    Resource mockResource = mock(Resource.class);

    mockResourceRequest = mock(ResourceRequest.class);
    when(mockResourceRequest.getAttributeValue()).thenReturn(new URI("myURI"));
    when(mockResourceRequest.getAttributeName()).thenReturn(new String("myName"));

    mockResourceResponse = mock(ResourceResponse.class);
    when(mockResourceResponse.getRequest()).thenReturn(mockResourceRequest);
    when(mockResourceResponse.getResource()).thenReturn(mockResource);

    mockPostResourcePlugin = mock(PostResourcePlugin.class);
    /*
     * We verify (see verification section of test) that PostResourcePlugin.process() receives a
     * ResourceResponse with a non-null ResourceRequest. We assume that it works correctly and
     * returns a ResourceResponse with a non-null ResourceRequest, so we return our
     * mockResouceResponse that contains a non-null ResourceRequest.
     */
    when(mockPostResourcePlugin.process(isA(ResourceResponse.class))).thenReturn(mockResourceResponse);

    List<PostResourcePlugin> mockPostResourcePlugins = new ArrayList<PostResourcePlugin>();
    mockPostResourcePlugins.add(mockPostResourcePlugin);

    eventAdmin = new MockEventProcessor();
    provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(), true, new Date());

    storageProvider = new MockMemoryStorageProvider();

    ArrayList<PostIngestPlugin> postIngestPlugins = new ArrayList<PostIngestPlugin>();
    postIngestPlugins.add(eventAdmin);

    mockFederationStrategy = mock(FederationStrategy.class);
    Result mockFederationResult = mock(Result.class);
    when(mockFederationResult.getMetacard()).thenReturn(new MetacardImpl());
    QueryRequest mockQueryRequest = mock(QueryRequest.class);
    Query mockQuery = mock(Query.class);
    when(mockQuery.getTimeoutMillis()).thenReturn(1L);
    when(mockQueryRequest.getQuery()).thenReturn(mockQuery);
    QueryResponseImpl queryResponse = new QueryResponseImpl(mockQueryRequest,
            Collections.singletonList(mockFederationResult), 1);
    when(mockFederationStrategy.federate(anyList(), anyObject())).thenReturn(queryResponse);

    federatedSources = createDefaultFederatedSourceList(true);

    MimeTypeResolver mimeTypeResolver = mock(MimeTypeResolver.class);
    MimeTypeToTransformerMapper mimeTypeToTransformerMapper = mock(MimeTypeToTransformerMapper.class);
    InputTransformer inputTransformer = mock(InputTransformer.class);
    when(inputTransformer.transform(any(InputStream.class))).thenReturn(new MetacardImpl());
    when(mimeTypeToTransformerMapper.findMatches(any(Class.class), any(MimeType.class)))
            .thenReturn(Collections.singletonList(inputTransformer));

    mockRemoteDeleteOperations = mock(RemoteDeleteOperations.class);

    FrameworkProperties frameworkProperties = new FrameworkProperties();
    frameworkProperties.setAccessPlugins(new ArrayList<>());
    frameworkProperties.setPolicyPlugins(new ArrayList<>());
    frameworkProperties.setCatalogProviders(Collections.singletonList((CatalogProvider) provider));
    frameworkProperties.setPostResource(mockPostResourcePlugins);
    frameworkProperties.setFederationStrategy(mockFederationStrategy);
    frameworkProperties.setFilterBuilder(new GeotoolsFilterBuilder());
    frameworkProperties.setPreIngest(new ArrayList<>());
    frameworkProperties.setPostIngest(postIngestPlugins);
    frameworkProperties.setPreQuery(new ArrayList<>());
    frameworkProperties.setPostQuery(new ArrayList<>());
    frameworkProperties.setPreResource(new ArrayList<>());
    frameworkProperties.setPostResource(new ArrayList<>());
    frameworkProperties.setQueryResponsePostProcessor(mock(QueryResponsePostProcessor.class));
    frameworkProperties.setStorageProviders(Collections.singletonList(storageProvider));
    frameworkProperties.setMimeTypeMapper(new MimeTypeMapperImpl(Collections.singletonList(mimeTypeResolver)));
    frameworkProperties.setMimeTypeToTransformerMapper(mimeTypeToTransformerMapper);

    List<FederatedSource> federatedSourceList = new ArrayList<>();
    if (federatedSources != null) {
        for (FederatedSource source : federatedSources) {
            federatedSourceList.add(source);
        }
    }
    frameworkProperties.setFederatedSources(federatedSourceList);

    defaultAttributeValueRegistry = new DefaultAttributeValueRegistryImpl();
    frameworkProperties.setDefaultAttributeValueRegistry(defaultAttributeValueRegistry);

    attributeInjector = spy(new AttributeInjectorImpl(new AttributeRegistryImpl()));
    frameworkProperties.setAttributeInjectors(Collections.singletonList(attributeInjector));

    uuidGenerator = mock(UuidGenerator.class);
    when(uuidGenerator.generateUuid()).thenReturn(UUID.randomUUID().toString());

    sourceActionRegistry = mock(ActionRegistry.class);
    when(sourceActionRegistry.list(any())).thenReturn(Collections.emptyList());

    final SourcePoller<SourceStatus> mockStatusSourcePoller = mock(SourcePoller.class);
    doAnswer(invocationOnMock -> Optional
            .of(((Source) invocationOnMock.getArguments()[0]).isAvailable() ? SourceStatus.AVAILABLE
                    : SourceStatus.UNAVAILABLE)).when(mockStatusSourcePoller)
                            .getCachedValueForSource(any(Source.class));
    final SourcePoller<Set<ContentType>> mockContentTypesSourcePoller = mock(SourcePoller.class);
    doAnswer(invocationOnMock -> Optional.of(((Source) invocationOnMock.getArguments()[0]).getContentTypes()))
            .when(mockContentTypesSourcePoller).getCachedValueForSource(any(Source.class));

    OperationsSecuritySupport opsSecurity = new OperationsSecuritySupport();
    MetacardFactory metacardFactory = new MetacardFactory(mimeTypeToTransformerMapper, uuidGenerator);
    OperationsMetacardSupport opsMetacard = new OperationsMetacardSupport(frameworkProperties, metacardFactory);
    SourceOperations sourceOperations = new SourceOperations(frameworkProperties, sourceActionRegistry,
            mockStatusSourcePoller, mockContentTypesSourcePoller);
    TransformOperations transformOperations = new TransformOperations(frameworkProperties);
    Historian historian = new Historian();
    historian.setHistoryEnabled(false);

    QueryOperations queryOperations = new QueryOperations(frameworkProperties, sourceOperations, opsSecurity,
            opsMetacard);
    OperationsStorageSupport opsStorage = new OperationsStorageSupport(sourceOperations, queryOperations);
    opsStorage.setHistorian(historian);

    OperationsCatalogStoreSupport opsCatStore = new OperationsCatalogStoreSupport(frameworkProperties,
            sourceOperations);
    CreateOperations createOperations = new CreateOperations(frameworkProperties, queryOperations,
            sourceOperations, opsSecurity, opsMetacard, opsCatStore, opsStorage);
    UpdateOperations updateOperations = new UpdateOperations(frameworkProperties, queryOperations,
            sourceOperations, opsSecurity, opsMetacard, opsCatStore, opsStorage);
    deleteOperations = new DeleteOperations(frameworkProperties, queryOperations, sourceOperations, opsSecurity,
            opsMetacard);

    deleteOperations.setOpsCatStoreSupport(opsCatStore);

    ResourceOperations resOps = new ResourceOperations(frameworkProperties, queryOperations, opsSecurity) {
        @Override
        protected ResourceInfo getResourceInfo(ResourceRequest resourceRequest, String site,
                boolean isEnterprise, StringBuilder federatedSite, Map<String, Serializable> requestProperties,
                boolean fanoutEnabled) throws ResourceNotSupportedException, ResourceNotFoundException {
            URI uri = null;
            Metacard metacard = new MetacardImpl();

            try {
                uri = new URI("myURI");
            } catch (URISyntaxException e) {
            }

            return new ResourceInfo(metacard, uri);
        }
    };

    updateOperations.setHistorian(historian);
    deleteOperations.setHistorian(historian);

    framework = new CatalogFrameworkImpl(createOperations, updateOperations, deleteOperations, queryOperations,
            resOps, sourceOperations, transformOperations);
    // Conditionally bind objects if framework properties are setup
    if (!CollectionUtils.isEmpty(frameworkProperties.getCatalogProviders())) {
        sourceOperations.bind(provider);
    }
    sourceOperations.bind(storageProvider);

    resourceFramework = new CatalogFrameworkImpl(createOperations, updateOperations, deleteOperations,
            queryOperations, resOps, sourceOperations, transformOperations);
    // Conditionally bind objects if framework properties are setup
    if (!CollectionUtils.isEmpty(frameworkProperties.getCatalogProviders())) {
        sourceOperations.bind(provider);
    }
    sourceOperations.bind(storageProvider);

    ThreadContext.bind(mock(Subject.class));
}

From source file:ddf.catalog.security.ingest.IngestPluginTest.java

License:Open Source License

@Test
public void testCreateProcessGoodSubject() throws Exception {
    IngestPlugin ingestPlugin = new IngestPlugin();
    ingestPlugin.setPermissionStrings(new String[] { "role=admin" });

    Subject subject = mock(Subject.class);
    when(subject.isPermitted(any(Permission.class))).thenReturn(true);
    ThreadContext.bind(subject);

    CreateRequest request = mock(CreateRequest.class);
    CreateRequest response = ingestPlugin.process(request);
    assertThat(response, not(equalTo(null)));

    ThreadContext.unbindSubject();/*from ww  w.  j av a 2s . c  om*/
}