org.apache.shiro.util.StringUtils Java Examples
The following examples show how to use
org.apache.shiro.util.StringUtils.
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: MySimpleHash.java From cms with Apache License 2.0 | 6 votes |
public MySimpleHash(String algorithmName, Object source, Object salt, int hashIterations) throws CodecException, UnknownAlgorithmException { this.hexEncoded = null; this.base64Encoded = null; if (!StringUtils.hasText(algorithmName)) { throw new NullPointerException("algorithmName argument cannot be null or empty."); } else { this.algorithmName = algorithmName; this.iterations = Math.max(1, hashIterations); ByteSource saltBytes = null; if (salt != null) { saltBytes = this.convertSaltToBytes(salt); this.salt = saltBytes; } ByteSource sourceBytes = this.convertSourceToBytes(source); this.hash(sourceBytes, saltBytes, hashIterations); } }
Example #2
Source File: LoginForm.java From tapestry-security with Apache License 2.0 | 6 votes |
@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 #3
Source File: LdapRealm.java From zeppelin with Apache License 2.0 | 6 votes |
static String getSystemPassword(String hadoopSecurityCredentialPath, String keystorePass) { String password = ""; try { Configuration configuration = new Configuration(); configuration.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, hadoopSecurityCredentialPath); CredentialProvider provider = CredentialProviderFactory.getProviders(configuration).get(0); CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(keystorePass); if (credEntry != null) { password = new String(credEntry.getCredential()); } } catch (IOException e) { throw new ShiroException("Error from getting credential entry from keystore", e); } if (org.apache.commons.lang3.StringUtils.isEmpty(password)) { throw new ShiroException("Error getting SystemPassword from the provided keystore:" + keystorePass + ", in path:" + hadoopSecurityCredentialPath); } return password; }
Example #4
Source File: SimpleHash.java From nano-framework with Apache License 2.0 | 5 votes |
/** * * @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 #5
Source File: KeycloakAdminClient.java From nexus3-keycloak-plugin with Apache License 2.0 | 5 votes |
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 #6
Source File: NexusKeycloakClient.java From nexus3-keycloak-plugin with Apache License 2.0 | 5 votes |
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 #7
Source File: NexusKeycloakClient.java From nexus3-keycloak-plugin with Apache License 2.0 | 5 votes |
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 #8
Source File: RedisCacheManager.java From hunt-admin with Apache License 2.0 | 5 votes |
@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 #9
Source File: HttpFilter.java From MultimediaDesktop with Apache License 2.0 | 5 votes |
protected int toPort(Object mappedValue) { String[] ports = (String[]) mappedValue; if (ports == null || ports.length == 0) { return getPort(); } if (ports.length > 1) { throw new ConfigurationException("PortFilter can only be configured with a single port. You have " + "configured " + ports.length + ": " + StringUtils.toString(ports)); } return Integer.parseInt(ports[0]); }
Example #10
Source File: LdapRealm.java From zeppelin with Apache License 2.0 | 5 votes |
protected void onInit() { super.onInit(); if (!org.apache.commons.lang3.StringUtils.isEmpty(this.hadoopSecurityCredentialPath) && getContextFactory() != null) { ((JndiLdapContextFactory) getContextFactory()).setSystemPassword( getSystemPassword(this.hadoopSecurityCredentialPath, keystorePass)); } }
Example #11
Source File: GoogleCloudDatastoreFactory.java From nexus-blobstore-google-cloud with Eclipse Public License 1.0 | 5 votes |
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 #12
Source File: HashedCredentialsMatcher.java From nano-framework with Apache License 2.0 | 5 votes |
/** * Creates an instance using the specified {@link #getHashAlgorithmName() hashAlgorithmName} to hash submitted * credentials. * @param hashAlgorithmName the {@code Hash} {@link org.apache.shiro.crypto.hash.Hash#getAlgorithmName() algorithmName} * to use when performing hashes for credentials matching. * @since 1.1 */ public HashedCredentialsMatcher(String hashAlgorithmName) { this(); if (!StringUtils.hasText(hashAlgorithmName) ) { throw new IllegalArgumentException("hashAlgorithmName cannot be null or empty."); } this.hashAlgorithm = hashAlgorithmName; }
Example #13
Source File: PortFilter.java From tapestry-security with Apache License 2.0 | 5 votes |
protected int toPort(Object mappedValue) { String[] ports = (String[]) mappedValue; if (ports == null || ports.length == 0) { return getPort(); } if (ports.length > 1) { throw new ConfigurationException("PortFilter can only be configured with a single port. You have " + "configured " + ports.length + ": " + StringUtils.toString(ports)); } return Integer.parseInt(ports[0]); }
Example #14
Source File: SecurityExceptionHandlerAssistant.java From tapestry-security with Apache License 2.0 | 5 votes |
@Override public Object handleRequestException(Throwable exception, List<Object> exceptionContext) throws IOException { if (securityService.isAuthenticated()) { String unauthorizedPage = loginContextService.getUnauthorizedPage(); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (!StringUtils.hasText(unauthorizedPage)) return null; Page page = pageCache.get(unauthorizedPage); renderer.renderPageResponse(page); return null; } loginContextService.saveRequest(); return loginContextService.getLoginPage(); }
Example #15
Source File: LoginForm.java From tapestry-security with Apache License 2.0 | 5 votes |
public String getLoginMessage() { if (StringUtils.hasText(loginMessage)) { return loginMessage; } else { return " "; } }
Example #16
Source File: EditUserValidator.java From java-course-ee with MIT License | 5 votes |
public void validate(Object o, Errors errors) { EditUserCommand command = (EditUserCommand) 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."); } }
Example #17
Source File: SignupValidator.java From java-course-ee with MIT License | 5 votes |
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 #18
Source File: WebSecurityModule.java From seed with Mozilla Public License 2.0 | 5 votes |
/** * This method is copied from the same method in Shiro in class DefaultFilterChainManager. */ private String[] toNameConfigPair(String token) throws ConfigurationException { String[] pair = token.split("\\[", 2); String name = StringUtils.clean(pair[0]); if (name == null) { throw new IllegalArgumentException("Filter name not found for filter chain definition token: " + token); } String config = null; if (pair.length == 2) { config = StringUtils.clean(pair[1]); //if there was an open bracket, it assumed there is a closing bracket, so strip it too: config = config.substring(0, config.length() - 1); config = StringUtils.clean(config); //backwards compatibility prior to implementing SHIRO-205: //prior to SHIRO-205 being implemented, it was common for end-users to quote the config inside brackets //if that config required commas. We need to strip those quotes to get to the interior quoted definition //to ensure any existing quoted definitions still function for end users: if (config != null && config.startsWith("\"") && config.endsWith("\"")) { String stripped = config.substring(1, config.length() - 1); stripped = StringUtils.clean(stripped); //if the stripped value does not have any internal quotes, we can assume that the entire config was //quoted and we can use the stripped value. if (stripped != null && stripped.indexOf('"') == -1) { config = stripped; } //else: //the remaining config does have internal quotes, so we need to assume that each comma delimited //pair might be quoted, in which case we need the leading and trailing quotes that we stripped //So we ignore the stripped value. } } return new String[]{name, config}; }
Example #19
Source File: JsetsAuthorizationFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 5 votes |
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException { Subject subject = getSubject(request, response); //未认证 if (null == subject.getPrincipal()) { if (CommonUtils.isAjax(WebUtils.toHttp(request))) { CommonUtils.ajaxFailed(WebUtils.toHttp(response) ,HttpServletResponse.SC_UNAUTHORIZED ,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED ,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED); } saveRequestAndRedirectToLogin(request, response); //未授权 } else { if (CommonUtils.isAjax(WebUtils.toHttp(request))) { CommonUtils.ajaxFailed(WebUtils.toHttp(response) ,HttpServletResponse.SC_FORBIDDEN ,ShiroProperties.REST_CODE_AUTH_FORBIDDEN ,ShiroProperties.REST_MESSAGE_AUTH_FORBIDDEN); }else{ String unauthorizedUrl = getUnauthorizedUrl(); if (StringUtils.hasText(unauthorizedUrl)) { WebUtils.issueRedirect(request, response, unauthorizedUrl); } else { WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN); } } } return false; }
Example #20
Source File: GenericOAuth2ApiBinding.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public T getAccessToken(String code) { Map<String, String> parameters = createParameters(); hasText(config.getAppId(), "'appId' is empty, please check the configure"); parameters.put(DEFAULT_PARAM_CLIENT_ID, config.getAppId()); hasText(config.getAppSecret(), "'appSecret' is empty, please check the configure"); parameters.put(DEFAULT_PARAM_CLIENT_SECRET, config.getAppSecret()); // Consistent with the previous getAuthorizeCodeUrl step hasText(config.getRedirectUrl(), "'redirect_url' is empty, please check the configure"); parameters.put(DEFAULT_PARAM_REDIRECT_URI, config.getRedirectUrl()); // grant_type OAuth2GrantType gt = (grantType() != null) ? grantType() : OAuth2GrantType.getDefault(); parameters.put(DEFAULT_PARAM_GRANT_TYPE, gt.name().toLowerCase()); if (gt == OAuth2GrantType.AUTHORIZATION_CODE) { isTrue(StringUtils.hasText(code), "'code' is empty, please check the configure"); parameters.put(DEFAULT_PARAM_AUTH_CODE, code); } // Post process postGetAccessTokenUrl(parameters); String url = parametersToUrl(getAccessTokenUriEndpoint(), parameters); log.info("Get accessToken url: '{}'", url); // Send request String accessTokenJson = restTemplate.getForObject(url.toString(), String.class); if (isBlank(accessTokenJson)) { throw new SnsApiBindingException("OAuth2 response accessToken empty"); } log.info("Response accessToken: {}", accessTokenJson); return ((Oauth2AccessToken) newResponseMessage(1)).build(accessTokenJson).validate(); }
Example #21
Source File: GenericOAuth2ApiBinding.java From super-cloudops with Apache License 2.0 | 5 votes |
@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 #22
Source File: IamShiroFilterFactoryBean.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * 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 #23
Source File: IamShiroFilterFactoryBean.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * 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 #24
Source File: IamShiroFilterFactoryBean.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * See: {@link ShiroFilterFactoryBean#applyLoginUrlIfNecessary} * * @param filter */ private void applyLoginUrlIfNecessary(Filter filter) { String loginUrl = getLoginUrl(); if (StringUtils.hasText(loginUrl) && (filter instanceof AccessControlFilter)) { AccessControlFilter acFilter = (AccessControlFilter) filter; // only apply the login url if they haven't explicitly configured // one already: String existingLoginUrl = acFilter.getLoginUrl(); if (AccessControlFilter.DEFAULT_LOGIN_URL.equals(existingLoginUrl)) { acFilter.setLoginUrl(loginUrl); } } }
Example #25
Source File: AbstractPermittingAuthorizingRealm.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * 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 #26
Source File: EnhancedWildcardPermission.java From super-cloudops with Apache License 2.0 | 5 votes |
protected void initWildcardString(String wildcardString, boolean caseSensitive) { wildcardString = StringUtils.clean(wildcardString); if (isBlank(wildcardString)) { throw new IllegalArgumentException( "Wildcard string cannot be null or empty. Make sure permission strings are properly formatted."); } checkWildcard(wildcardString); if (!caseSensitive) { wildcardString = wildcardString.toLowerCase(); } List<String> permits = CollectionUtils.asList(wildcardString.split(PERMIT_DIVIDER_TOKEN)); permitParts = new ArrayList<Set<String>>(); for (String permit : permits) { Set<String> permitPart = CollectionUtils.asSet(permit.split(PERMIT_PART_DIVIDER_TOKEN)); if (permitPart.isEmpty()) { throw new IllegalArgumentException( "Wildcard string cannot contain parts with only dividers. Make sure permission strings are properly formatted."); } permitParts.add(permitPart); } if (permitParts.isEmpty()) { throw new IllegalArgumentException( "Wildcard string cannot contain only dividers. Make sure permission strings are properly formatted."); } }
Example #27
Source File: GoogleCloudStorageFactory.java From nexus-blobstore-google-cloud with Eclipse Public License 1.0 | 5 votes |
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 #28
Source File: CasStatelessAuthorizingRealm.java From shiro-cas-spring-boot-starter with Apache License 2.0 | 5 votes |
/** * 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 #29
Source File: DefaultShiroServiceImpl.java From ueboot with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 获取用户的权限列表 * * @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 #30
Source File: CasAuthenticatingFilter.java From shiro-cas-spring-boot-starter with Apache License 2.0 | 5 votes |
@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; }