Example usage for org.apache.shiro.cache Cache get

List of usage examples for org.apache.shiro.cache Cache get

Introduction

In this page you can find the example usage for org.apache.shiro.cache Cache get.

Prototype

public V get(K key) throws CacheException;

Source Link

Document

Returns the Cached value stored under the specified key or null if there is no Cache entry for that key .

Usage

From source file:br.com.criativasoft.opendevice.restapi.auth.BearerAuthRealm.java

License:Open Source License

public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    BearerAuthToken authToken = (BearerAuthToken) token;

    String authTokenS = (String) authToken.getPrincipal();

    DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
    Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE);

    DataManager context = manager.getDataManager();

    String apiKey = (String) cache.get(authTokenS);

    // The token is API_KEY
    if (apiKey == null && authToken.isApikey()) {
        apiKey = authTokenS;/*from ww  w  .ja va  2 s .  c o m*/
    }

    if (apiKey == null)
        log.warn("ApiKey not found for token : " + authTokenS);

    if (apiKey != null && context instanceof ApiDataManager) {

        AccountDao dao = ((ApiDataManager) context).getAccountDao();

        UserAccount userAccount = dao.getUserAccountByApiKey(apiKey);

        if (userAccount != null) {
            Account account = userAccount.getOwner();

            AccountType type = userAccount.getType();

            AccountPrincipal principal = new AccountPrincipal(userAccount.getUser().getId(),
                    userAccount.getId(), account.getUuid(), type);

            // todo: load permission tags into AuthenticationInfo
            return new SimpleAuthenticationInfo(principal, authToken.getCredentials(), "BearerTokenRealm");
        }
    }

    return null;
}

From source file:br.com.criativasoft.opendevice.restapi.auth.GoogleAuthRealm.java

License:Open Source License

public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    GoogleAuthToken authToken = (GoogleAuthToken) token;

    String authTokenS = (String) authToken.getPrincipal();

    DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
    Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE);

    DataManager context = manager.getDataManager();
    AccountDao dao = ((ApiDataManager) context).getAccountDao();

    String userAccountID = (String) cache.get(authTokenS);

    if (userAccountID == null) {

        log.warn("ApiKey not found for token : " + authTokenS);

        try {/*w w  w. ja  v  a  2s . c  om*/
            String url = "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=";
            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = client.execute(new HttpGet(url + authTokenS));
            String bodyAsString = EntityUtils.toString(response.getEntity());

            if (response.getStatusLine().getStatusCode() == 200) {

                String appID = ODev.getConfig().getString(OpenDeviceConfig.ConfigKey.google_appid);

                if (appID == null) {
                    throw new AuthenticationException("Google AppID not configured !");
                }

                JsonNode json = new ObjectMapper().readTree(bodyAsString);

                String aud = json.get("aud").asText();

                // TODO: need validate, but this may ne used for another appletavions IDs (ALEXA, MIDDLEWARE)
                //                    if(!appID.equals(aud)){
                //                        throw new AuthenticationException("Invalid Google Token");
                //                    }

                UserDao userDao = ((ApiDataManager) context).getUserDao();
                User user = userDao.getUser(json.get("email").asText());

                // Store in cahe
                if (user != null) {
                    userAccountID = "" + user.getLasLoginAccount().getId();
                    cache.put(authTokenS, userAccountID);
                }

            } else {
                throw new AuthenticationException("Invalid Google Token");
            }

        } catch (IOException ex) {
            throw new AuthenticationException(ex.getMessage());
        }
    }

    if (userAccountID != null && context instanceof ApiDataManager) {

        UserAccount userAccount = dao.getUserAccountByID(Long.parseLong(userAccountID));

        if (userAccount != null) {
            Account account = userAccount.getOwner();

            AccountType type = userAccount.getType();

            AccountPrincipal principal = new AccountPrincipal(userAccount.getUser().getId(),
                    userAccount.getId(), account.getUuid(), type);

            // todo: load permission tags into AuthenticationInfo
            return new SimpleAuthenticationInfo(principal, authToken.getCredentials(), "BearerTokenRealm");
        }
    }

    return null;
}

From source file:br.com.criativasoft.opendevice.wsrest.resource.OAuthRest.java

License:Open Source License

@POST
@Path("/token")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)//www .j  ava 2 s.c  o m
public Response tokenPost(@Context HttpServletRequest request, MultivaluedMap<String, String> formParams)
        throws OAuthSystemException {

    OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

    Long userAccountID;

    try {
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(
                new ParameterizedHttpRequest(request, formParams));

        DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
        Cache<Object, Object> cache = securityManager.getCacheManager()
                .getCache(AuthenticationFilter.TOKEN_CACHE);

        String clientID = oauthRequest.getParam(OAuth.OAUTH_CLIENT_ID);

        // do checking for different grant types
        if (GrantType.AUTHORIZATION_CODE.toString().equals(oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE))) {

            String codeParam = oauthRequest.getParam(OAuth.OAUTH_CODE);
            userAccountID = (Long) cache.get(codeParam);

            if (userAccountID == null) {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_GRANT)
                        .setErrorDescription("invalid authorization code").buildJSONMessage();

                return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
            } else {
                cache.remove(codeParam); // not required anymore
            }
        }
        //            else if (
        //                    oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString()))
        //            {
        //                if (!Common.PASSWORD.equals(oauthRequest.getPassword())
        //                        ||!Common.USERNAME.equals(oauthRequest.getUsername()))
        //                {
        //                    OAuthResponse response =
        //                            OAuthASResponse.errorResponse(
        //                                    HttpServletResponse.SC_BAD_REQUEST).setError(
        //                                    OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription(
        //                                    "invalid username or password").buildJSONMessage();
        //
        //                    return Response.status(response.getResponseStatus()).entity(
        //                            response.getBody()).build();
        //                }
        else if (GrantType.REFRESH_TOKEN.toString().equals(oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE))) {

            String key = oauthRequest.getParam(OAuth.OAUTH_REFRESH_TOKEN);

            UserAccount account = accountDao.getUserAccountByApiKey(key);

            if (account == null) {
                OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(OAuthError.TokenResponse.INVALID_GRANT)
                        .setErrorDescription("Invalid REFRESH_TOKEN").buildJSONMessage();

                return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
            } else {
                userAccountID = account.getId();
            }
        } else {
            throw OAuthProblemException.error("Invalid Rrequest");
        }

        String accessToken = oauthIssuerImpl.accessToken();

        // This token will be handled by AuthenticationFilter
        UserAccount userAccount = accountDao.getUserAccountByID(userAccountID);
        ApiKey apiKeyUser = userAccount.getKeys().iterator().next();
        cache.put(accessToken, apiKeyUser.getKey());

        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken).setRefreshToken(apiKeyUser.getKey()).setExpiresIn("3600")
                .buildJSONMessage();

        return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
    } catch (OAuthProblemException e) {
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();

        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
    }
}

From source file:com.github.zbiljic.shiro.cache.infinispan.InfinispanManagerTest.java

License:Open Source License

@Test
public void testLazyCacheManagerCreationWithoutCallingInit() {
    EmbeddedCacheManager infinispanCacheManager = cacheManager.getCacheManager();
    assertNull(infinispanCacheManager);/*from www  .  ja v a2  s .c o m*/

    //don't call init here - the Infinispan EmbeddedCacheManager should be lazily created
    //because of the default Shiro infinispan.xml file in the classpath.  Just acquire a cache:
    Cache<String, String> cache = cacheManager.getCache("test");

    //now assert that an internal EmbeddedCacheManager has been created:
    infinispanCacheManager = cacheManager.getCacheManager();
    assertNotNull(infinispanCacheManager);

    assertNotNull(cache);
    cache.put("hello", "world");
    String value = cache.get("hello");
    assertNotNull(value);
    assertEquals(value, "world");
}

From source file:com.github.zbiljic.shiro.cache.infinispan.InfinispanManagerTest.java

License:Open Source License

@Test
public void testProvideCustomCacheManager() throws Exception {
    // create custom cache manager
    EmbeddedCacheManager customCacheManager = new DefaultCacheManager(
            cacheManager.getCacheManagerConfigFileInputStream());
    assertNotNull(customCacheManager);/*w ww  .ja  v a 2s . c o  m*/

    BasicCacheContainer infinispanCacheContainer = cacheManager.getCacheContainer();
    assertNull(infinispanCacheContainer);

    cacheManager.setCacheContainer(customCacheManager);

    //now assert that an internal EmbeddedCacheManager has been created:
    infinispanCacheContainer = cacheManager.getCacheContainer();
    assertNotNull(infinispanCacheContainer);

    // Acquire the cache:
    Cache<String, String> cache = cacheManager.getCache("test");

    assertNotNull(cache);
    cache.put("hello", "world");
    String value = cache.get("hello");
    assertNotNull(value);
    assertEquals(value, "world");

    // Don't forget to stop the custom cache manager
    customCacheManager.stop();
}

From source file:com.wms.studio.utils.MemCacheUtil.java

License:Apache License

public static Object getCacheValueObject(String key) {
    Cache<String, Object> cache = SpringContextHelper.getMemcache(SessionKeyConstant.SYSTEM_MEMCACHE_KEY);
    if (cache == null) {
        return null;
    }/*from   w  w w .  j  a va  2s  . co  m*/
    return cache.get(key);
}

From source file:de.iai.ilcd.security.IlcdSecurityRealm.java

License:Open Source License

/**
 * {@inheritDoc} <br />//from  w ww  .ja v  a 2s.c o m
 * Original code from {@link AuthorizingRealm}, <code>null</code> check removed (guest support)
 */
@Override
protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {

    AuthorizationInfo info = null;

    if (log.isTraceEnabled()) {
        log.trace("Retrieving AuthorizationInfo for principals [" + principals + "]");
    }

    Cache<Object, AuthorizationInfo> cache = this.getAvailableAuthorizationCache();
    if (cache != null) {
        if (log.isTraceEnabled()) {
            log.trace("Attempting to retrieve the AuthorizationInfo from cache.");
        }
        Object key = this.getAuthorizationCacheKey(principals);
        info = cache.get(key);
        if (log.isTraceEnabled()) {
            if (info == null) {
                log.trace("No AuthorizationInfo found in cache for principals [" + principals + "]");
            } else {
                log.trace("AuthorizationInfo found in cache for principals [" + principals + "]");
            }
        }
    }

    if (info == null) {
        // Call template method if the info was not found in a cache
        info = this.doGetAuthorizationInfo(principals);
        // If the info is not null and the cache has been created, then cache the authorization info.
        if (info != null && cache != null) {
            if (log.isTraceEnabled()) {
                log.trace("Caching authorization info for principals: [" + principals + "].");
            }
            Object key = this.getAuthorizationCacheKey(principals);
            cache.put(key, info);
        }
    }

    return info;
}

From source file:org.ehcache.integrations.shiro.EhcacheShiroManagerTest.java

License:Apache License

@Test
public void testGetCache() throws Exception {
    EhcacheShiroManager cacheManager = new EhcacheShiroManager();

    try {/*from w  ww. ja va2  s .c o m*/
        Cache<Object, Object> someCache = cacheManager.getCache("someCache");
        Assert.assertNotNull(someCache);

        final String key = "key";
        final String value = "value";
        Assert.assertNull(someCache.put(key, value));
        Assert.assertEquals(value, someCache.get(key));
    } finally {
        cacheManager.destroy();
    }
}

From source file:org.sonatype.security.realms.url.URLRealm.java

License:Open Source License

private AuthenticationInfo getAuthInfoFromCache(UsernamePasswordToken token) {
    // get cache//from w  w  w .  ja v a2  s.  co  m
    Cache authCache = this.getAuthenticationCache();

    // check if null
    if (authCache != null) {
        // the supports method already only allows supported tokens
        String username = token.getUsername();
        String pass = String.valueOf(token.getPassword());

        String cacheKey = this.getAuthenticationCacheKey(username, pass);
        if (authCache.get(cacheKey) != null) {
            // return an AuthenticationInfo if we found the username in the cache
            return this.buildAuthenticationInfo(username, null);
        }
    }

    return null;
}

From source file:org.youi.framework.core.web.PageScriptFactory.java

License:Apache License

public String getPageScript(String sessionId, String pageId) {
    Cache<String, String> scriptCache = cacheManager.getCache("org.youi.common.PageScriptFactory");

    return scriptCache.get(pageId + sessionId);
}