List of usage examples for org.apache.shiro SecurityUtils getSecurityManager
public static SecurityManager getSecurityManager() throws UnavailableSecurityManagerException
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;/*from www.j a v a2 s. com*/ 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 www.ja v a 2s . co 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)//from www . ja v a 2 s . co 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:cn.powerdash.libsystem.common.security.SecurityContext.java
License:Open Source License
/** * Description: ??/*from w ww . j a v a2 s . co m*/ * * @param userId */ public static void clearAuthzCache(String userName) { RealmSecurityManager sm = (RealmSecurityManager) SecurityUtils.getSecurityManager(); for (Realm realm : sm.getRealms()) { if (realm instanceof ShiroJdbcRealm) { ShiroJdbcRealm jdbcRealm = (ShiroJdbcRealm) realm; SimplePrincipalCollection spc = new SimplePrincipalCollection(userName, realm.getName()); jdbcRealm.clearAuthorizationCache(spc); } } LOGGER.info("Authorization cache cleared for user: {}", userName); }
From source file:cn.powerdash.libsystem.common.security.SecurityContext.java
License:Open Source License
/** * Description: ??/*from w w w . j av a 2s .co m*/ * * @param users */ public static void clearAllAuthzCache() { CacheManager cm = (CacheManager) ((CachingSecurityManager) SecurityUtils.getSecurityManager()) .getCacheManager(); cm.getCache(AppConfigUtil.getConfig(CACHE_NAME_AUTHZ)).clear(); }
From source file:cn.powerdash.libsystem.common.security.SecurityContext.java
License:Open Source License
/** * Description: ??/*from w w w. ja v a 2s .co m*/ * * @param userId */ public static void clearAuthcCache(String userName) { RealmSecurityManager sm = (RealmSecurityManager) SecurityUtils.getSecurityManager(); for (Realm realm : sm.getRealms()) { if (realm instanceof ShiroJdbcRealm) { ShiroJdbcRealm jdbcRealm = (ShiroJdbcRealm) realm; SimplePrincipalCollection spc = new SimplePrincipalCollection(userName, realm.getName()); jdbcRealm.clearAuthenticationCache(spc); } } }
From source file:cn.powerdash.libsystem.common.security.SecurityContext.java
License:Open Source License
/** * Description: ??// www . ja v a 2 s. c om * * @param users */ public static void clearAllAuthcCache() { CacheManager cm = (CacheManager) ((CachingSecurityManager) SecurityUtils.getSecurityManager()) .getCacheManager(); cm.getCache(AppConfigUtil.getConfig(CACHE_NAME_AUTHC)).clear(); }
From source file:co.edu.uniandes.csw.appmarketplace.services.QuestionService.java
@POST @StatusCreated//from w w w . j a va 2 s . co m @Consumes("application/json") public QuestionDTO createQuestion(QuestionDTO dto) { Subject currentUser = SecurityUtils.getSubject(); UserDTO loggedUser = (UserDTO) SecurityUtils.getSubject().getSession().getAttribute("Client"); if (loggedUser != null) { client = clientLogic.getClientByUsername(loggedUser.getUserName()); } else { client = null; } if (client == null) { Logger.getLogger(QuestionService.class.getName()).log(Level.SEVERE, null, new Exception("User is not a registered client")); return null; } Map<String, String> userAttributes = (Map<String, String>) currentUser.getPrincipals() .oneByType(java.util.Map.class); //Se modifico para poder hacer el test //AppDTO app = appLogic.getApp(dto.getApp().getId()); AppDTO app = dto.getApp(); if (app != null) { dto.setApp(app); dto.setDate(new Date()); dto.setClient(client); dto.setEmail(userAttributes.get("email")); ApplicationRealm realm = (ApplicationRealm) ((RealmSecurityManager) SecurityUtils.getSecurityManager()) .getRealms().iterator().next(); Client cli = realm.getClient(); Account account = cli.getResource(app.getDeveloper().getUserId(), Account.class); return questionLogic.doQuestion(dto, app.getDeveloper(), app, account.getEmail()); } return null; }
From source file:co.edu.uniandes.csw.mpusedvehicle.services.UserService.java
private Account createUser(UserDTO user) { ApplicationRealm realm = ((ApplicationRealm) ((RealmSecurityManager) SecurityUtils.getSecurityManager()) .getRealms().iterator().next()); Client client = realm.getClient();//from w w w. jav a 2s . com Application application = client.getResource(realm.getApplicationRestUrl(), Application.class); Account acct = client.instantiate(Account.class); acct.setUsername(user.getUserName()); acct.setPassword(user.getPassword()); acct.setEmail(user.getEmail()); acct.setGivenName(user.getName()); acct.setSurname(user.getName()); acct.setStatus(AccountStatus.ENABLED); GroupList groups = application.getGroups(); for (Group grp : groups) { if (grp.getName().equals(user.getRole())) { acct = application.createAccount(acct); acct.addGroup(grp); break; } } return acct; }
From source file:co.edu.uniandes.csw.musicstore.services.UserService.java
private Account createUser(UserDTO user) { ApplicationRealm realm = ((ApplicationRealm) ((RealmSecurityManager) SecurityUtils.getSecurityManager()) .getRealms().iterator().next()); Client client = realm.getClient();/*w ww . ja va2s . c o m*/ Application application = client.getResource(realm.getApplicationRestUrl(), Application.class); Account acct = client.instantiate(Account.class); acct.setUsername(user.getUserName()); acct.setPassword(user.getPassword()); acct.setEmail(user.getEmail()); acct.setGivenName(user.getName()); acct.setSurname(user.getLastName()); acct.setStatus(AccountStatus.ENABLED); GroupList groups = application.getGroups(); for (Group grp : groups) { if (grp.getName().equals(user.getRole())) { acct = application.createAccount(acct); acct.addGroup(grp); break; } } return acct; }