Java Code Examples for org.apache.shiro.util.StringUtils#hasText()

The following examples show how to use org.apache.shiro.util.StringUtils#hasText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoginForm.java    From tapestry-security with Apache License 2.0 6 votes vote down vote up
@OnEvent(value = EventConstants.SUCCESS, component = LOGIN_FORM_ID)
public Object onSuccessfulLogin() throws IOException
{
	if (StringUtils.hasText(successURL)) {
		if ("^".equals(successURL))
			return pageRenderLinkSource.createPageRenderLink(componentResources.getPage().getClass());
		return new URL(successURL);
	}

	if (redirectToSavedUrl) {
		String requestUri = loginContextService.getSuccessPage();
		if (!requestUri.startsWith("/") && !requestUri.startsWith("http")) {
		    requestUri = "/" + requestUri;
		}
		loginContextService.redirectToSavedRequest(requestUri);
		return null;
	}
	return loginContextService.getSuccessPage();
}
 
Example 2
Source File: GoogleCloudStorageFactory.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 5 votes vote down vote up
Storage create(final BlobStoreConfiguration configuration) throws Exception {
  StorageOptions.Builder builder = StorageOptions.newBuilder().setTransportOptions(transportOptions());

  String credentialFile = configuration.attributes(CONFIG_KEY).get(CREDENTIAL_FILE_KEY, String.class);
  if (StringUtils.hasText(credentialFile)) {
    ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream(credentialFile));
    logger.debug("loaded {} from {} for Google storage client", credentials, credentialFile);
    builder.setCredentials(credentials);
    builder.setProjectId(getProjectId(credentialFile));
  }

  return builder.build().getService();
}
 
Example 3
Source File: SimpleHash.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param algorithmName  the {@link java.security.MessageDigest MessageDigest} algorithm name to use when
 *                       performing the hash.
 * @param source         the source object to be hashed.
 * @param salt           the salt to use for the hash
 * @param hashIterations the number of times the {@code source} argument hashed for attack resiliency.
 * @throws CodecException            if either Object constructor argument cannot be converted into a byte array.
 * @throws UnknownAlgorithmException if the {@code algorithmName} is not available.
 */
public SimpleHash(String algorithmName, Object source, Object salt, int hashIterations) throws CodecException, UnknownAlgorithmException {
    if (!StringUtils.hasText(algorithmName)) {
        throw new NullPointerException("algorithmName argument cannot be null or empty.");
    }
    this.algorithmName = algorithmName;
    this.iterations = Math.max(DEFAULT_ITERATIONS, hashIterations);
    ByteSource saltBytes = null;
    if (salt != null) {
        saltBytes = convertSaltToBytes(salt);
        this.salt = saltBytes;
    }
    ByteSource sourceBytes = convertSourceToBytes(source);
    hash(sourceBytes, saltBytes, hashIterations);
}
 
Example 4
Source File: RedisCacheManager.java    From hunt-admin with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
    if (!StringUtils.hasText(name)) {
        throw new IllegalArgumentException("Cache name cannot be null or empty.");
    }
    log.debug("redis cache manager get cache name is :{}", name);
    Cache cache = (Cache) redisTemplate.opsForValue().get(name);
    if (cache == null) {
        cache = new RedisCache<>(redisTemplate);
        redisTemplate.opsForValue().set(SystemConstant.shiro_cache_prefix + name, cache);
    }
    return cache;
}
 
Example 5
Source File: SignupValidator.java    From java-course-ee with MIT License 5 votes vote down vote up
public void validate(Object o, Errors errors) {
    SignupCommand command = (SignupCommand) o;
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.username.empty", "Please specify a username.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email.empty", "Please specify an email address.");
    if (StringUtils.hasText(command.getEmail()) && !Pattern.matches(SIMPLE_EMAIL_REGEX, command.getEmail().toUpperCase())) {
        errors.rejectValue("email", "error.email.invalid", "Please enter a valid email address.");
    }
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.password.empty", "Please specify a password.");
}
 
Example 6
Source File: NexusKeycloakClient.java    From nexus3-keycloak-plugin with Apache License 2.0 5 votes vote down vote up
public Set<User> findUserByCriteria(UserSearchCriteria criteria) {
    String search = "";

    if (StringUtils.hasText(criteria.getUserId())) {
        search = criteria.getUserId();
    } else if (StringUtils.hasText(criteria.getEmail())) {
        search = criteria.getEmail();
    }

    List<UserRepresentation> users = this.keycloakAdminClient.findUsers(search);
    if (users != null) {
        users = users.stream().filter(UserRepresentation::isEnabled).collect(Collectors.toList());
    }
    return KeycloakMapper.toUsers(getSource(), users);
}
 
Example 7
Source File: NexusKeycloakClient.java    From nexus3-keycloak-plugin with Apache License 2.0 5 votes vote down vote up
public boolean authenticate(UsernamePasswordToken token) {
    String principal = token.getUsername();
    String credentials = new String(token.getPassword());
    AccessTokenResponse accessTokenResponse = this.keycloakAdminClient.obtainAccessToken(principal, credentials);

    return accessTokenResponse != null && StringUtils.hasText(accessTokenResponse.getToken());
}
 
Example 8
Source File: KeycloakAdminClient.java    From nexus3-keycloak-plugin with Apache License 2.0 5 votes vote down vote up
public UserRepresentation getUser(String userNameOrEmail) {
    if (!StringUtils.hasText(userNameOrEmail)) {
        return null;
    }

    HttpMethod<List<UserRepresentation>> httpMethod = getHttp().get("/admin/realms/%s/users",
                                                                    this.config.getRealm());

    boolean isEmail = isEmail(userNameOrEmail);
    if (isEmail) {
        httpMethod.param("email", userNameOrEmail);
    } else {
        httpMethod.param("username", userNameOrEmail);
    }
    List<UserRepresentation> users = httpMethod.authentication()
                                               .response()
                                               .json(new TypeReference<List<UserRepresentation>>() {})
                                               .execute();

    if (users != null) {
        for (UserRepresentation user : users) {
            // Note: We need to avoid someone try to register email as username to fake others.
            boolean matched = isEmail
                              ? userNameOrEmail.equals(user.getEmail())
                              : userNameOrEmail.equals(user.getUsername());
            if (matched) {
                return user;
            }
        }
    }
    return null;
}
 
Example 9
Source File: GenericOAuth2ApiBinding.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public String getAuthorizeCodeUrl(String state, Map<String, String> queryParams) {
	Map<String, String> parameters = createParameters();

	// Client ID
	hasText(config.getAppId(), "'appId' is empty, please check the configure");
	parameters.put(DEFAULT_PARAM_CLIENT_ID, config.getAppId());

	// State
	String stateVal = StringUtils.hasText(state) ? state : state();
	parameters.put(DEFAULT_PARAM_STATE, stateVal);

	// Scope
	if (StringUtils.hasText(scope())) {
		parameters.put(DEFAULT_PARAM_SCOPE, scope());
	}

	// Redirect URL
	hasText(config.getRedirectUrl(), "'redirect_url' is empty, please check the configure");
	// Extra query parameters
	String redirectUrl = config.getRedirectUrl();
	if (queryParams != null && !queryParams.isEmpty()) {
		redirectUrl = WebUtils2.applyQueryURL(redirectUrl, queryParams);
	}
	parameters.put(DEFAULT_PARAM_REDIRECT_URI, WebUtils2.safeEncodeURL(redirectUrl));

	// Response type
	OAuth2ResponseType rt = (responseType() != null) ? responseType() : OAuth2ResponseType.getDefault();
	parameters.put(DEFAULT_PARAM_RESPONSE_TYPE, rt.name().toLowerCase());

	// Post process
	postGetAuthorizationCodeUrl(parameters);

	String url = parametersToUrl(getAuthorizationCodeUriEndpoint(), parameters);
	log.info("Get authorization code url: '{}'", url);

	return url.toString();
}
 
Example 10
Source File: IamShiroFilterFactoryBean.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * See: {@link ShiroFilterFactoryBean#applyUnauthorizedUrlIfNecessary}
 *
 * @param filter
 */
private void applyUnauthorizedUrlIfNecessary(Filter filter) {
	String unauthorizedUrl = getUnauthorizedUrl();
	if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter)) {
		AuthorizationFilter authzFilter = (AuthorizationFilter) filter;
		// only apply the unauthorizedUrl if they haven't explicitly
		// configured one already:
		String existingUnauthorizedUrl = authzFilter.getUnauthorizedUrl();
		if (existingUnauthorizedUrl == null) {
			authzFilter.setUnauthorizedUrl(unauthorizedUrl);
		}
	}
}
 
Example 11
Source File: IamShiroFilterFactoryBean.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * See: {@link ShiroFilterFactoryBean#applySuccessUrlIfNecessary}
 *
 * @param filter
 */
private void applySuccessUrlIfNecessary(Filter filter) {
	String successUrl = getSuccessUrl();
	if (StringUtils.hasText(successUrl) && (filter instanceof AuthenticationFilter)) {
		AuthenticationFilter authcFilter = (AuthenticationFilter) filter;
		// only apply the successUrl if they haven't explicitly configured
		// one already:
		String existingSuccessUrl = authcFilter.getSuccessUrl();
		if (AuthenticationFilter.DEFAULT_SUCCESS_URL.equals(existingSuccessUrl)) {
			authcFilter.setSuccessUrl(successUrl);
		}
	}
}
 
Example 12
Source File: AbstractPermittingAuthorizingRealm.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Split a string into a list of not empty and trimmed strings, delimiter is
 * a comma.
 * 
 * @param s
 *            the input string
 * @return the list of not empty and trimmed strings
 */
protected List<String> splitPermitString(String s) {
	List<String> list = new ArrayList<String>();
	String[] elements = StringUtils.split(s, ',');
	if (elements != null && elements.length > 0) {
		for (String element : elements) {
			if (StringUtils.hasText(element)) {
				list.add(element.trim());
			}
		}
	}
	return list;
}
 
Example 13
Source File: DefaultShiroServiceImpl.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 获取用户的权限列表
 *
 * @param roleNames 角色名称集合
 * @return 用户权限列表
 */
@Override
public Set<String> getRolePermission(String username,Set<String> roleNames) {

    List<Permission> permissionList = this.permissionRepository.findByRoleNameIn(roleNames);

    Set<String> names = new HashSet<>();
    for (Permission p : permissionList) {
        if(StringUtils.hasText(p.getResource().getPermission())){
            names.add(p.getResource().getPermission());
        }
    }
    return names;

}
 
Example 14
Source File: CasAuthenticatingFilter.java    From shiro-cas-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
	HttpServletRequest httpRequest = WebUtils.toHttp(request);
	String ticket = httpRequest.getParameter(TICKET_PARAMETER);
	CasToken token = new CasToken(RemoteAddrUtils.getRemoteAddr(httpRequest));
	if(StringUtils.hasText(ticket)) {
		token.setTicket(ticket);
	}
	token.setUsername(httpRequest.getRemoteUser());
	return token;
}
 
Example 15
Source File: CasStatelessAuthorizingRealm.java    From shiro-cas-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Split a string into a list of not empty and trimmed strings, delimiter is a comma.
 * 
 * @param s the input string
 * @return the list of not empty and trimmed strings
 */
private List<String> split(String s) {
    List<String> list = new ArrayList<String>();
    String[] elements = StringUtils.split(s, ',');
    if (elements != null && elements.length > 0) {
        for (String element : elements) {
            if (StringUtils.hasText(element)) {
                list.add(element.trim());
            }
        }
    }
    return list;
}
 
Example 16
Source File: GoogleCloudDatastoreFactory.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 5 votes vote down vote up
Datastore create(final BlobStoreConfiguration configuration) throws Exception {
  DatastoreOptions.Builder builder = DatastoreOptions.newBuilder().setTransportOptions(transportOptions());

  String credentialFile = configuration.attributes(CONFIG_KEY).get(CREDENTIAL_FILE_KEY, String.class);
  if (StringUtils.hasText(credentialFile)) {
    ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream(credentialFile));
    logger.debug("loaded {} from {} for Google Datastore client", credentials, credentialFile);
    builder.setCredentials(credentials);
    builder.setProjectId(getProjectId(credentialFile));
  }

  return builder.build().getService();
}
 
Example 17
Source File: Helpers.java    From jqm with Apache License 2.0 4 votes vote down vote up
static void checkConfiguration(String nodeName, DbConn cnx)
{
    // Node
    List<Node> nodes = Node.select(cnx, "node_select_by_key", nodeName);
    if (nodes.size() == 0)
    {
        throw new JqmInitError("The node does not exist. It must be referenced (CLI option createnode) before it can be used");
    }
    Node nn = nodes.get(0);

    if (!StringUtils.hasText(nn.getDlRepo()) || !StringUtils.hasText(nn.getRepo()) || !StringUtils.hasText(nn.getTmpDirectory()))
    {
        throw new JqmInitError(
                "The node does not have all its paths specified. Check node configuration (or recreate it with the CLI).");
    }

    // Default queue
    List<Queue> defaultQueues = Queue.select(cnx, "q_select_default");
    if (defaultQueues.size() == 0)
    {
        throw new JqmInitError("There is no default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }
    if (defaultQueues.size() > 1)
    {
        throw new JqmInitError(
                "There is more than one default queue. Correct this (for example with CLI option -u, or with the web admin)");
    }

    // Deployment parameters
    int i = cnx.runSelectSingle("dp_select_count_for_node", Integer.class, nn.getId());
    if (i == 0)
    {
        jqmlogger.warn(
                "This node is not bound to any queue. Either use the GUI to bind it or use CLI option -u to bind it to the default queue");
    }

    // Roles
    List<RRole> roles = RRole.select(cnx, "role_select_by_key", "administrator");
    if (roles.size() != 1)
    {
        throw new JqmInitError("The 'administrator' role does not exist. It is needed for the APIs. Run CLI option -u to create it.");
    }

    // Mail session
    i = cnx.runSelectSingle("jndi_select_count_for_key", Integer.class, "mail/default");
    if (i == 0L)
    {
        throw new JqmInitError("Mail session named mail/default does not exist but is required for the engine to run"
                + ". Use CLI option -u to create an empty one or use the admin web GUI to create it.");
    }
}
 
Example 18
Source File: AuthorizationFilter.java    From tapestry-security with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the response when access has been denied.  It behaves as follows:
 * <ul>
 * <li>If the {@code Subject} is unknown<sup><a href="#known">[1]</a></sup>:
 * <ol><li>The incoming request will be saved and they will be redirected to the login page for authentication
 * (via the {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
 * method).</li>
 * <li>Once successfully authenticated, they will be redirected back to the originally attempted page.</li></ol>
 * </li>
 * <li>If the Subject is known:</li>
 * <ol>
 * <li>The HTTP {@link HttpServletResponse#SC_UNAUTHORIZED} header will be set (401 Unauthorized)</li>
 * <li>If the {@link #getUnauthorizedUrl() unauthorizedUrl} has been configured, a redirect will be issued to that
 * URL.  Otherwise the 401 response is rendered normally</li>
 * </ul>
 * <code><a name="known">[1]</a></code>: A {@code Subject} is 'known' when
 * <code>subject.{@link org.apache.shiro.subject.Subject#getPrincipal() getPrincipal()}</code> is not {@code null},
 * which implicitly means that the subject is either currently authenticated or they have been remembered via
 * 'remember me' services.
 *
 * @param request  the incoming <code>ServletRequest</code>
 * @param response the outgoing <code>ServletResponse</code>
 * @return {@code false} always for this implementation.
 * @throws IOException if there is any servlet error.
 */
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

    Subject subject = getSubject(request, response);
    // If the subject isn't identified, redirect to login URL
    if (subject.getPrincipal() == null) {
        saveRequestAndRedirectToLogin(request, response);
    } else {
        // If subject is known but not authorized, redirect to the unauthorized URL if there is one
        // If no unauthorized URL is specified, just return an unauthorized HTTP status code
        String unauthorizedUrl = getUnauthorizedUrl();
        //SHIRO-142 - ensure that redirect _or_ error code occurs - both cannot happen due to response commit:
        if (StringUtils.hasText(unauthorizedUrl)) {
            WebUtils.issueRedirect(request, response, unauthorizedUrl);
        } else {
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
    return false;
}
 
Example 19
Source File: RedisCache.java    From ueboot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public RedisCache(RedisTemplate<Object, Object> redisTemplate,String namespace) {
    this.redisTemplate = redisTemplate;
    if(StringUtils.hasText(namespace)){
        keyNamespace = namespace;
    }
}
 
Example 20
Source File: SmsAuthorizingRealm.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * Assertion account information
 *
 * @param acc
 * @param token
 */
private void assertAccountInfo(IamPrincipalInfo acc, SmsAuthenticationToken token) {
	if (acc == null || !StringUtils.hasText(acc.getPrincipal())) {
		throw new UnknownAccountException(bundle.getMessage("GeneralAuthorizingRealm.notAccount", token.getPrincipal()));
	}
}