Example usage for org.apache.shiro.util StringUtils hasText

List of usage examples for org.apache.shiro.util StringUtils hasText

Introduction

In this page you can find the example usage for org.apache.shiro.util StringUtils hasText.

Prototype

public static boolean hasText(String str) 

Source Link

Document

Check whether the given String has actual text.

Usage

From source file:me.buom.shiro.filter.HmacAuthenticationFilter.java

License:Apache License

@Override
public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    HttpServletRequest httpRequest = WebUtils.toHttp(request);
    if (StringUtils.hasText(httpRequest.getHeader("Content-MD5"))) {
        HmacRequestWrapper requestWrapper = new HmacRequestWrapper(httpRequest);
        super.doFilterInternal(requestWrapper, response, chain);
    } else {//from ww w .j  a v a2s . c o m
        super.doFilterInternal(request, response, chain);
    }
}

From source file:me.buom.shiro.util.SimpleHmacBuilder.java

License:Apache License

public String buildStringToSign(HmacToken token) {
    httpRequest = WebUtils.toHttp(token.getRequest());
    String stringToSign = String.format(Locale.US, "%s\n%s\n%s\n%s\n%s", httpRequest.getMethod(),
            StringUtils.hasText(getHeader("Content-MD5")) ? DigestUtils.md5Hex(toByteArray(httpRequest)) : "",
            //getHeader("Content-MD5"),
            //getHeader("Content-Type"),
            httpRequest.getContentType(), getHeader("Date"), httpRequest.getRequestURI());

    return stringToSign;
}

From source file:net.cloudkit.enterprises.infrastructure.shiro.PermissionsAuthorizationExpandFilter.java

License:Apache License

@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    Subject subject = this.getSubject(request, response);
    if (subject.getPrincipal() == null) {
        this.saveRequestAndRedirectToLogin(request, response);
    } else {//from   w  w  w.  j ava  2s .co m
        if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
            String unauthorizedUrl = this.getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(401);
            }
        } else {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json; charset=utf-8");
            httpResponse.setCharacterEncoding("UTF-8");
            // httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter out = response.getWriter();
            out.println("{\"isDeniedPermission\":true, \"message\":\"???\"}");
            out.flush();
            out.close();
        }
    }

    return false;
}

From source file:org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm.java

License:Apache License

public void setMemberAttributeValueTemplate(String template) {
    if (!StringUtils.hasText(template)) {
        String msg = "User DN template cannot be null or empty.";
        throw new IllegalArgumentException(msg);
    }//from  ww w .java 2s  . co m
    int index = template.indexOf(MEMBER_SUBSTITUTION_TOKEN);
    if (index < 0) {
        String msg = "Member attribute value template must contain the '" + MEMBER_SUBSTITUTION_TOKEN
                + "' replacement token to understand how to " + "parse the group members.";
        throw new IllegalArgumentException(msg);
    }
    String prefix = template.substring(0, index);
    String suffix = template.substring(prefix.length() + MEMBER_SUBSTITUTION_TOKEN.length());
    this.memberAttributeValuePrefix = prefix;
    this.memberAttributeValueSuffix = suffix;
}

From source file:org.apache.isis.security.shiro.IsisLdapRealm.java

License:Apache License

public void setUniqueMemberAttributeValueTemplate(String template) {
    if (!StringUtils.hasText(template)) {
        String msg = "User DN template cannot be null or empty.";
        throw new IllegalArgumentException(msg);
    }/*from   ww w.ja  va2 s . co  m*/
    int index = template.indexOf(UNIQUEMEMBER_SUBSTITUTION_TOKEN);
    if (index < 0) {
        String msg = "UniqueMember attribute value template must contain the '"
                + UNIQUEMEMBER_SUBSTITUTION_TOKEN + "' replacement token to understand how to "
                + "parse the group members.";
        throw new IllegalArgumentException(msg);
    }
    String prefix = template.substring(0, index);
    String suffix = template.substring(prefix.length() + UNIQUEMEMBER_SUBSTITUTION_TOKEN.length());
    this.uniqueMemberAttributeValuePrefix = prefix;
    this.uniqueMemberAttributeValueSuffix = suffix;
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

License:Apache License

/**
* Set Member Attribute Template for LDAP.
* 
* @param template//w  ww  .j a v  a  2 s .com
*            DN template to be used to query ldap.
* @throws IllegalArgumentException
*             if template is empty or null.
*/
public void setMemberAttributeValueTemplate(String template) {
    if (!StringUtils.hasText(template)) {
        String msg = "User DN template cannot be null or empty.";
        throw new IllegalArgumentException(msg);
    }
    int index = template.indexOf(MEMBER_SUBSTITUTION_TOKEN);
    if (index < 0) {
        String msg = "Member attribute value template must contain the '" + MEMBER_SUBSTITUTION_TOKEN
                + "' replacement token to understand how to " + "parse the group members.";
        throw new IllegalArgumentException(msg);
    }
    String prefix = template.substring(0, index);
    String suffix = template.substring(prefix.length() + MEMBER_SUBSTITUTION_TOKEN.length());
    this.memberAttributeValuePrefix = prefix;
    this.memberAttributeValueSuffix = suffix;
}

From source file:org.apache.zeppelin.utils.ZeppelinRealm.java

License:Apache License

@Override
protected void onInit() {
    super.onInit();

    // This is an in-memory realm only - no need for an additional cache when we're already
    // as memory-efficient as we can be.

    Ini ini = getIni();/*from   ww w.  j a v  a 2s  . c o  m*/
    String resourcePath = getResourcePath();

    if (!CollectionUtils.isEmpty(this.users) || !CollectionUtils.isEmpty(this.roles)) {
        if (!CollectionUtils.isEmpty(ini)) {
            log.warn("Users or Roles are already populated.  Configured Ini instance will be ignored.");
        }
        if (StringUtils.hasText(resourcePath)) {
            log.warn("Users or Roles are already populated.  resourcePath '{}' will be ignored.", resourcePath);
        }

        log.debug("Instance is already populated with users or roles.  No additional user/role population "
                + "will be performed.");
        return;
    }

    if (CollectionUtils.isEmpty(ini)) {
        log.debug("No INI instance configuration present.  Checking resourcePath...");

        if (StringUtils.hasText(resourcePath)) {
            log.debug("Resource path {} defined.  Creating INI instance.", resourcePath);
            ini = Ini.fromResourcePath(resourcePath);
            if (!CollectionUtils.isEmpty(ini)) {
                setIni(ini);
            }
        }
    }

    if (CollectionUtils.isEmpty(ini)) {
        String msg = "Ini instance and/or resourcePath resulted in null or empty Ini configuration.  Cannot "
                + "load account data.";
        throw new IllegalStateException(msg);
    }

    processDefinitions(ini);
}

From source file:org.ow2.proactive.iam.core.realms.LdapRealm.java

License:Open Source License

/**
 * Sets the User Distinguished Name (DN) template to use when creating User DNs at runtime.  A User DN is an LDAP
 * fully-qualified unique user identifier which is required to establish a connection with the LDAP
 * directory to authenticate users and query for authorization information.
 * <h2>Usage</h2>/* w w w.  j a  v a 2 s  .c o m*/
 * User DN formats are unique to the LDAP directory's schema, and each environment differs - you will need to
 * specify the format corresponding to your directory.  You do this by specifying the full User DN as normal, but
 * but you use a <b>{@code {0}}</b> placeholder token in the string representing the location where the
 * user's submitted principal (usually a username or uid) will be substituted at runtime.
 * <p/>
 * For example,  if your directory
 * uses an LDAP {@code uid} attribute to represent usernames, the User DN for the {@code jsmith} user may look like
 * this:
 * <p/>
 * <pre>uid=jsmith,ou=users,dc=mycompany,dc=com</pre>
 * <p/>
 * in which case you would set this property with the following template value:
 * <p/>
 * <pre>uid=<b>{0}</b>,ou=users,dc=mycompany,dc=com</pre>
 * <p/>
 * If no template is configured, the raw {@code AuthenticationToken}
 * {@link AuthenticationToken#getPrincipal() principal} will be used as the LDAP principal.  This is likely
 * incorrect as most LDAP directories expect a fully-qualified User DN as opposed to the raw uid or username.  So,
 * ensure you set this property to match your environment!
 *
 * @param template the User Distinguished Name template to use for runtime substitution
 * @throws IllegalArgumentException if the template is null, empty, or does not contain the
 *                                  {@code {0}} substitution token.
 * @see LdapContextFactory#getLdapContext(Object,Object)
 */
public void setUserDnTemplate(String template) throws IllegalArgumentException {
    if (!StringUtils.hasText(template)) {
        String msg = "User DN template cannot be null or empty.";
        throw new IllegalArgumentException(msg);
    }
    int index = template.indexOf(USERDN_SUBSTITUTION_TOKEN);
    if (index < 0) {
        String msg = "User DN template must contain the '" + USERDN_SUBSTITUTION_TOKEN
                + "' replacement token to understand where to "
                + "insert the runtime authentication principal.";
        throw new IllegalArgumentException(msg);
    }
    String prefix = template.substring(0, index);
    String suffix = template.substring(prefix.length() + USERDN_SUBSTITUTION_TOKEN.length());
    log.debug("Determined user DN prefix [{}] and suffix [{}]", prefix, suffix);
    this.userDnPrefix = prefix;
    this.userDnSuffix = suffix;
}

From source file:org.ow2.proactive.iam.core.realms.LdapRealm.java

License:Open Source License

/**
 * Returns the LDAP User Distinguished Name (DN) to use when acquiring an
 * {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}.
 * <p/>//from w  w w.ja va 2s.  c  o m
 * If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct
 * the User DN by substituting the specified {@code principal} into the configured template.  If the
 * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly
 * (indicating that the submitted authentication token principal <em>is</em> the User DN).
 *
 * @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}.
 * @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}.
 * @throws IllegalArgumentException if the method argument is null or empty
 * @throws IllegalStateException    if the {@link #getUserDnTemplate userDnTemplate} has not been set.
 * @see LdapContextFactory#getLdapContext(Object, Object)
 */
protected String getUserDn(String principal) throws IllegalArgumentException, IllegalStateException {
    if (!StringUtils.hasText(principal)) {
        throw new IllegalArgumentException("User principal cannot be null or empty for User DN construction.");
    }
    String prefix = getUserDnPrefix();
    String suffix = getUserDnSuffix();
    if (prefix == null && suffix == null) {
        log.debug("userDnTemplate property has not been configured, indicating the submitted "
                + "AuthenticationToken's principal is the same as the User DN.  Returning the method argument "
                + "as is.");
        return principal;
    }

    int prefixLength = prefix != null ? prefix.length() : 0;
    int suffixLength = suffix != null ? suffix.length() : 0;
    StringBuilder sb = new StringBuilder(prefixLength + principal.length() + suffixLength);
    if (prefixLength > 0) {
        sb.append(prefix);
    }
    sb.append(principal);
    if (suffixLength > 0) {
        sb.append(suffix);
    }
    return sb.toString();
}

From source file:org.ow2.proactive.iam.rest.controllers.SecurityController.java

License:Open Source License

@RequestMapping("/login")
public String login(String username, char[] password) {
    Subject currentUser = SecurityUtils.getSubject();
    if (StringUtils.hasText(username) && password != null) {
        try {//w  w w. ja v a 2  s .c  o  m
            currentUser.login(new UsernamePasswordToken(username, password));
            if (currentUser.isAuthenticated()) {
                Session session = currentUser.getSession();
                // TODO need a service class to transform shiro permissions into AuthorizationInfo
                session.setAttribute("authorization",
                        new AuthorizationInfo("admin", "liu", session.getId().toString()));
            }
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
            return "login";
        }
        return "redirect:home";
    } else {
        return "login";
    }
}