List of usage examples for org.apache.shiro.cache Cache put
public V put(K key, V value) throws CacheException;
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 {// ww w . j a v a2 s. com 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.AuthRest.java
License:Open Source License
private Response doLogin(Subject currentUser, String username, String password, boolean isApiKey) { LOG.debug("Using ApiKey (" + isApiKey + "), username : " + username); Account account = null;// w ww . j a v a 2s.c o m String authtoken = null; boolean logged = false; // Login using: ApiKey if (isApiKey) { account = accountDao.getAccountByApiKey(username); // Generate and cache the 'AuthToken', this will be used in AuthenticationFilter // This token will be used in BearerTokenRealm // TODO: Need configure expire using EhCache if (account != null) { // NOTE(RR): To simplify the development of clients, AuthToken and API Key will be the AccountUUID. // This can be changed in the future (issues #57) // authtoken = UUID.randomUUID().toString(); authtoken = account.getUuid(); // Add token to cache (thid will be used in BearerTokenRealm) DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils .getSecurityManager(); Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE); cache.put(authtoken, username); // username (is Api_Key in this case) logged = true; } // login using: Form } else if (!currentUser.isAuthenticated()) { try { User user = userDao.getUser(username); if (user == null) throw new AuthenticationException("Incorrect username"); // ckeck plain version (loaded from database) boolean passwordsMatch = password.equals(user.getPassword()); // Check encryption version (provided by user) if (!passwordsMatch) { HashingPasswordService service = new DefaultPasswordService(); passwordsMatch = service.passwordsMatch(password, user.getPassword()); } if (!passwordsMatch) throw new AuthenticationException("Incorrect password"); Set<UserAccount> uaccounts = user.getAccounts(); // Filter normal accounts uaccounts = uaccounts.stream().filter(accountx -> accountx.getType() != AccountType.DEVICE) .collect(Collectors.toSet()); if (uaccounts.isEmpty()) throw new AuthenticationException("No accounts for user"); if (uaccounts.size() > 1) { // TODO: Need return list and redirect to annother page... return ErrorResponse.status(Status.FORBIDDEN, "Multiple Accounts not supported for now !! (open ticket !)"); } AccountAuth token = new AccountAuth(uaccounts.iterator().next().getId(), user.getId()); //token.setRememberMe(false); // to be remembered across sessions currentUser.login(token); // currentUser.getSession(true).setTimeout(xxxxx); if (currentUser.isAuthenticated()) { AccountPrincipal principal = (AccountPrincipal) currentUser.getPrincipal(); logged = true; authtoken = principal.getAccountUUID(); user.setLastLogin(new Date()); } } catch (UnknownAccountException e) { return ErrorResponse.UNAUTHORIZED("Unknown Account"); } catch (IncorrectCredentialsException e) { return ErrorResponse.status(Status.FORBIDDEN, "Incorrect Credentials"); } catch (AuthenticationException e) { return ErrorResponse.UNAUTHORIZED(e.getMessage()); } } if (logged) { return noCache(Response.status(Status.OK).entity("{\"token\":\"" + authtoken + "\"}")); } else { return ErrorResponse.UNAUTHORIZED("Authentication Fail"); } }
From source file:br.com.criativasoft.opendevice.wsrest.resource.OAuthRest.java
License:Open Source License
@GET @Path("/authorize") public Response authorize(@Context HttpServletRequest request) throws URISyntaxException, OAuthSystemException { Subject subject = SecurityUtils.getSubject(); // Save request and go to login page if (!subject.isAuthenticated()) { WebUtils.saveRequest(request);//from w w w . j a va2 s.c o m URI uri = UriBuilder.fromUri("/login").build(); return Response.seeOther(uri).build(); } OAuthAuthzRequest oauthRequest; OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator()); try { oauthRequest = new OAuthAuthzRequest(request); // build response according to response_type String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE); OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse .authorizationResponse(request, HttpServletResponse.SC_FOUND); String authCode = oauthIssuerImpl.authorizationCode(); if (responseType.equals(ResponseType.CODE.toString())) { builder.setCode(authCode); } else { throw new IllegalArgumentException("responseType not allowed = " + responseType); } String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI); final OAuthResponse response = builder.location(redirectURI).buildQueryMessage(); URI url = new URI(response.getLocationUri()); // Store autentication code in Token cache to validade in next phase (method: tokenPost) DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager(); Cache<Object, Object> cache = securityManager.getCacheManager() .getCache(AuthenticationFilter.TOKEN_CACHE); AccountPrincipal principal = (AccountPrincipal) subject.getPrincipal(); cache.put(authCode, principal.getUserAccountID()); return Response.status(response.getResponseStatus()).location(url).build(); } catch (OAuthProblemException e) { final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND); String redirectUri = e.getRedirectUri(); if (OAuthUtils.isEmpty(redirectUri)) { throw new WebApplicationException( responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build()); } final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e) .location(redirectUri).buildQueryMessage(); final URI location = new URI(response.getLocationUri()); return responseBuilder.location(location).build(); } }
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)/* ww w . j a v a2 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);/* ww w. j a va2s .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);//from w w w .j a v a 2 s . c om 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 <T> void setCache(String key, T value) { Cache<String, Object> cache = SpringContextHelper.getMemcache(SessionKeyConstant.SYSTEM_MEMCACHE_KEY); if (cache == null) { return;//from w ww . j av a2 s . c om } cache.put(key, value); }
From source file:de.iai.ilcd.security.IlcdSecurityRealm.java
License:Open Source License
/** * {@inheritDoc} <br />// w w w.j av a 2 s .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 w w . ja va 2 s . com 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 void putUserInCache(String username, String pass) { // get cache/*from ww w . ja v a 2 s. co m*/ Cache authCache = this.getAuthenticationCache(); // check if null if (authCache != null) { authCache.put(this.getAuthenticationCacheKey(username, pass), Boolean.TRUE); this.logger.debug("Added user: '" + username + "' to cache."); } else { this.logger.debug("Authentication Cache is disabled."); } }