List of usage examples for org.springframework.util Assert isInstanceOf
public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier)
From source file:de.thorstenberger.examServer.ws.remoteusermanager.RadiusAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messageSourceAccessor.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); if (!StringUtils.isEmpty(configManager.getRadiusHost()) && !StringUtils.isEmpty(configManager.getRadiusSharedSecret())) { // Determine username final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); final String password = (authentication.getCredentials() == null) ? "NONE_PROVIDED" : (String) authentication.getCredentials(); UserBean remoteUserBean;/* ww w.j a va 2 s . co m*/ try { remoteUserBean = getRemoteUserInfos(username, password); try { User localUser = userManager.getUserByUsername(remoteUserBean.getLogin()); if (localUser.getRoles().contains("student") && !configManager.isStudentsLoginEnabled()) throw new AuthenticationServiceException("Login disabled for student role."); } catch (final UsernameNotFoundException e) { final User user = new User(); user.setEnabled(true); user.setUsername(remoteUserBean.getLogin()); user.setFirstName(remoteUserBean.getFirstName() == null ? "" : remoteUserBean.getFirstName()); user.setLastName(remoteUserBean.getName() == null ? "" : remoteUserBean.getName()); user.setEmail(remoteUserBean.getEmail() == null ? "" : remoteUserBean.getEmail()); user.setPassword(StringUtil.encodePassword(remoteUserBean.getPassword(), "SHA")); user.addRole(roleManager.getRole("student")); try { userManager.saveUser(user); } catch (final UserExistsException e2) { // should not happen throw new RuntimeException(e2); } } } catch (final AuthenticationServiceException e) { throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Invalid username or password.")); } final UserDetails userDetails = userManager.getUserByUsername(username); Object principalToReturn = userDetails; if (forcePrincipalAsString) { principalToReturn = userDetails.getUsername(); } return createSuccessAuthentication(principalToReturn, authentication, userDetails); } return null; }
From source file:eu.europeana.aas.acl.CassandraMutableAclService.java
@Override public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException { Assert.notNull(objectIdentity, "Object Identity required"); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN createAcl: objectIdentity: " + objectIdentity); }/*w w w . j a va2 s . c o m*/ // Need to retrieve the current principal, in order to know who "owns" // this ACL (can be changed later on) Authentication auth = SecurityContextHolder.getContext().getAuthentication(); PrincipalSid sid = new PrincipalSid(auth); AclObjectIdentity newAoi = new AclObjectIdentity(objectIdentity); newAoi.setOwnerId(sid.getPrincipal()); newAoi.setOwnerPrincipal(true); newAoi.setEntriesInheriting(false); try { aclRepository.saveAcl(newAoi); } catch (AclAlreadyExistsException e) { throw new AlreadyExistsException(e.getMessage(), e); } // Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc) Acl acl = readAclById(objectIdentity); Assert.isInstanceOf(MutableAcl.class, acl, "MutableAcl should be been returned"); if (LOG.isDebugEnabled()) { LOG.debug("END createAcl: acl: " + acl); } return (MutableAcl) acl; }
From source file:fr.insalyon.creatis.vip.api.rest.security.apikey.ApikeyAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(ApikeyAuthenticationToken.class, authentication, "Only ApikeyAuthenticationToken is supported"); User vipUser;//from w w w.jav a2s. c o m String apikey = authentication.getCredentials().toString(); try { vipUser = userDAO.getUserByApikey(apikey); } catch (DAOException e) { logger.error("error when getting user by apikey", e); logger.error("Doing as if there is an auth error"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } if (vipUser == null) { logger.info("Cant authenticate because apikey not found:" + apikey); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } logger.info("apikey OK for " + vipUser.getEmail()); UserDetails springUser; try { Map<Group, CoreConstants.GROUP_ROLE> groups = configurationBusiness.getUserGroups(vipUser.getEmail()); vipUser.setGroups(groups); springUser = new SpringCompatibleUser(vipUser); } catch (BusinessException e) { logger.error("error when getting user groups" + vipUser.getEmail(), e); logger.error("Doing as if there is an auth error"); throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } checkUserInfo(springUser); try { logger.info("successful logging for " + springUser.getUsername()); userDAO.resetNFailedAuthentications(springUser.getUsername()); } catch (DAOException e) { logger.error("Error reseting failed auth attemps ", e); } return new ApikeyAuthenticationToken(springUser, apikey); }
From source file:gov.nih.nci.system.security.acegi.authentication.GridAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("GridAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // Determine username String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true; UserDetails user = this.userCache.getUserFromCache(username); if (user == null) { cacheWasUsed = false;/*from ww w . j av a 2 s . co m*/ } try { X509Certificate x509Certificate = login(username, ((UsernamePasswordAuthenticationToken) authentication).getCredentials().toString()); GrantedAuthority dummyGrantedAuthority = new GrantedAuthorityImpl(SecurityConstants.DUMMY_ROLE); GrantedAuthority[] grantedAuthorities = new GrantedAuthority[1]; grantedAuthorities[0] = dummyGrantedAuthority; user = new X509User(username, ((UsernamePasswordAuthenticationToken) authentication).getCredentials().toString(), true, true, true, true, grantedAuthorities); ((X509User) user).setCertificate(x509Certificate); } catch (CredentialNotFoundException cnfe) { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } catch (Exception e) { if (loginModuleDisabled) throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); throw new AuthenticationServiceException("Login error :" + e.getMessage()); } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); Assert.notNull(((X509User) user).getCertificate(), "retrieveUser certificate returned null - a violation of the interface contract"); if (!cacheWasUsed) { this.userCache.putUserInCache(user); } //Invoke into X509AuthenticationProvider and return the user from there return x509AuthenticationProvider .authenticate(new X509AuthenticationToken(((X509User) user).getCertificate())); }
From source file:org.acegisecurity.acl.basic.jdbc.JdbcDaoImpl.java
/** * Responsible for covering a <code>AclObjectIdentity</code> to a <code>String</code> that can be located * in the RDBMS./*from ww w. jav a 2 s . c o m*/ * * @param aclObjectIdentity to locate * * @return the object identity as a <code>String</code> */ protected String convertAclObjectIdentityToString(AclObjectIdentity aclObjectIdentity) { // Ensure we can process this type of AclObjectIdentity Assert.isInstanceOf(NamedEntityObjectIdentity.class, aclObjectIdentity, "Only aclObjectIdentity of type NamedEntityObjectIdentity supported (was passed: " + aclObjectIdentity + ")"); NamedEntityObjectIdentity neoi = (NamedEntityObjectIdentity) aclObjectIdentity; // Compose the String we expect to find in the RDBMS return neoi.getClassname() + ":" + neoi.getId(); }
From source file:org.acegisecurity.context.HttpSessionContextIntegrationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Assert.isInstanceOf(HttpServletRequest.class, req, "ServletRequest must be an instance of HttpServletRequest"); Assert.isInstanceOf(HttpServletResponse.class, res, "ServletResponse must be an instance of HttpServletResponse"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (request.getAttribute(FILTER_APPLIED) != null) { // ensure that filter is only applied once per request chain.doFilter(request, response); return;//from ww w . java2 s .co m } HttpSession httpSession = null; try { httpSession = request.getSession(forceEagerSessionCreation); } catch (IllegalStateException ignored) { } boolean httpSessionExistedAtStartOfRequest = httpSession != null; SecurityContext contextBeforeChainExecution = readSecurityContextFromSession(httpSession); // Make the HttpSession null, as we don't want to keep a reference to it lying // around in case chain.doFilter() invalidates it. httpSession = null; if (contextBeforeChainExecution == null) { contextBeforeChainExecution = generateNewContext(); if (logger.isDebugEnabled()) { logger.debug("New SecurityContext instance will be associated with SecurityContextHolder"); } } else { if (logger.isDebugEnabled()) { logger.debug("Obtained a valid SecurityContext from ACEGI_SECURITY_CONTEXT to " + "associate with SecurityContextHolder: '" + contextBeforeChainExecution + "'"); } } int contextHashBeforeChainExecution = contextBeforeChainExecution.hashCode(); request.setAttribute(FILTER_APPLIED, Boolean.TRUE); // Create a wrapper that will eagerly update the session with the security context // if anything in the chain does a sendError() or sendRedirect(). // See SEC-398 OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper( response, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); // Proceed with chain try { // This is the only place in this class where SecurityContextHolder.setContext() is called SecurityContextHolder.setContext(contextBeforeChainExecution); chain.doFilter(request, responseWrapper); } finally { // This is the only place in this class where SecurityContextHolder.getContext() is called SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext(); // Crucial removal of SecurityContextHolder contents - do this before anything else. SecurityContextHolder.clearContext(); request.removeAttribute(FILTER_APPLIED); // storeSecurityContextInSession() might already be called by the response wrapper // if something in the chain called sendError() or sendRedirect(). This ensures we only call it // once per request. if (!responseWrapper.isSessionUpdateDone()) { storeSecurityContextInSession(contextAfterChainExecution, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); } if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder now cleared, as request processing completed"); } } }
From source file:org.acegisecurity.context.HttpSessionContextIntegrationFilter.java
/** * Gets the security context from the session (if available) and returns it. * <p/>/*w w w. ja va 2 s. c o m*/ * If the session is null, the context object is null or the context object stored in the session * is not an instance of SecurityContext it will return null. * <p/> * If <tt>cloneFromHttpSession</tt> is set to true, it will attempt to clone the context object * and return the cloned instance. * * @param httpSession the session obtained from the request. */ private SecurityContext readSecurityContextFromSession(HttpSession httpSession) { if (httpSession == null) { if (logger.isDebugEnabled()) { logger.debug("No HttpSession currently exists"); } return null; } // Session exists, so try to obtain a context from it. Object contextFromSessionObject = httpSession.getAttribute(ACEGI_SECURITY_CONTEXT_KEY); if (contextFromSessionObject == null) { if (logger.isDebugEnabled()) { logger.debug("HttpSession returned null object for ACEGI_SECURITY_CONTEXT"); } return null; } // We now have the security context object from the session. // Clone if required (see SEC-356) if (cloneFromHttpSession) { Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, "Context must implement Clonable and provide a Object.clone() method"); try { Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); if (!m.isAccessible()) { m.setAccessible(true); } contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } } if (!(contextFromSessionObject instanceof SecurityContext)) { if (logger.isWarnEnabled()) { logger.warn("ACEGI_SECURITY_CONTEXT did not contain a SecurityContext but contained: '" + contextFromSessionObject + "'; are you improperly modifying the HttpSession directly " + "(you should always use SecurityContextHolder) or using the HttpSession attribute " + "reserved for this class?"); } return null; } // Everything OK. The only non-null return from this method. return (SecurityContext) contextFromSessionObject; }
From source file:org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.java
protected Authentication createAuthentication(ServletRequest request) { Assert.isInstanceOf(HttpServletRequest.class, request, "ServletRequest must be an instance of HttpServletRequest"); AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key, userAttribute.getPassword(), userAttribute.getAuthorities()); auth.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request)); return auth;//from ww w. ja v a 2 s.c om }
From source file:org.acegisecurity.providers.ldap.authenticator.LdapShaPasswordEncoder.java
/** * Calculates the hash of password (and salt bytes, if supplied) and returns a base64 encoded concatenation * of the hash and salt, prefixed with {SHA} (or {SSHA} if salt was used). * * @param rawPass the password to be encoded. * @param salt the salt. Must be a byte array or null. * * @return the encoded password in the specified format * *//*ww w. j av a2 s . c om*/ public String encodePassword(String rawPass, Object salt) { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (java.security.NoSuchAlgorithmException e) { throw new LdapDataAccessException("No SHA implementation available!", e); } sha.update(rawPass.getBytes()); if (salt != null) { Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array"); sha.update((byte[]) salt); } byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt); String prefix; if (salt == null) { prefix = forceLowerCasePrefix ? SHA_PREFIX_LC : SHA_PREFIX; } else { prefix = forceLowerCasePrefix ? SSHA_PREFIX_LC : SSHA_PREFIX; } return prefix + new String(Base64.encodeBase64(hash)); }
From source file:org.acegisecurity.providers.ProviderManager.java
/** * Attempts to authenticate the passed {@link Authentication} object.<p>The list of {@link * AuthenticationProvider}s will be successively tried until an <code>AuthenticationProvider</code> indicates it * is capable of authenticating the type of <code>Authentication</code> object passed. Authentication will then * be attempted with that <code>AuthenticationProvider</code>.</p> * <p>If more than one <code>AuthenticationProvider</code> supports the passed <code>Authentication</code> * object, only the first <code>AuthenticationProvider</code> tried will determine the result. No subsequent * <code>AuthenticationProvider</code>s will be tried.</p> * * @param authentication the authentication request object. * * @return a fully authenticated object including credentials. * * @throws AuthenticationException if authentication fails. *///from w w w . j a va2 s .c o m public Authentication doAuthentication(Authentication authentication) throws AuthenticationException { Iterator iter = providers.iterator(); Class toTest = authentication.getClass(); AuthenticationException lastException = null; while (iter.hasNext()) { AuthenticationProvider provider = (AuthenticationProvider) iter.next(); if (provider.supports(toTest)) { logger.debug("Authentication attempt using " + provider.getClass().getName()); Authentication result = null; try { result = provider.authenticate(authentication); sessionController.checkAuthenticationAllowed(result); } catch (AuthenticationException ae) { lastException = ae; result = null; } if (result != null) { sessionController.registerSuccessfulAuthentication(result); publishEvent(new AuthenticationSuccessEvent(result)); return result; } } } if (lastException == null) { lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } // Publish the event String className = exceptionMappings.getProperty(lastException.getClass().getName()); AbstractAuthenticationEvent event = null; if (className != null) { try { Class clazz = getClass().getClassLoader().loadClass(className); Constructor constructor = clazz .getConstructor(new Class[] { Authentication.class, AuthenticationException.class }); Object obj = constructor.newInstance(new Object[] { authentication, lastException }); Assert.isInstanceOf(AbstractAuthenticationEvent.class, obj, "Must be an AbstractAuthenticationEvent"); event = (AbstractAuthenticationEvent) obj; } catch (ClassNotFoundException ignored) { } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } catch (InstantiationException ignored) { } catch (InvocationTargetException ignored) { } } if (event != null) { publishEvent(event); } else { if (logger.isDebugEnabled()) { logger.debug("No event was found for the exception " + lastException.getClass().getName()); } } // Throw the exception throw lastException; }