Search in sources :

Example 81 with Principal

use of java.security.Principal in project cas by apereo.

the class PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction method constructCredentialsFromRequest.

@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        LOGGER.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }
    LOGGER.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) PrincipalBearingCredential(org.apereo.cas.adaptors.trusted.authentication.principal.PrincipalBearingCredential) Principal(java.security.Principal)

Example 82 with Principal

use of java.security.Principal in project gitblit by gitblit.

the class AuthenticationManager method authenticate.

/**
	 * Authenticate a user based on HTTP request parameters.
	 *
	 * Authentication by custom HTTP header, servlet container principal, X509Certificate, cookie,
	 * and finally BASIC header.
	 *
	 * @param httpRequest
	 * @param requiresCertificate
	 * @return a user object or null
	 */
@Override
public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
    // Check if this request has already been authenticated, and trust that instead of re-processing
    String reqAuthUser = (String) httpRequest.getAttribute(Constants.ATTRIB_AUTHUSER);
    if (!StringUtils.isEmpty(reqAuthUser)) {
        logger.debug("Called servlet authenticate when request is already authenticated.");
        return userManager.getUserModel(reqAuthUser);
    }
    // try to authenticate by servlet container principal
    if (!requiresCertificate) {
        Principal principal = httpRequest.getUserPrincipal();
        if (principal != null) {
            String username = principal.getName();
            if (!StringUtils.isEmpty(username)) {
                boolean internalAccount = userManager.isInternalAccount(username);
                UserModel user = userManager.getUserModel(username);
                if (user != null) {
                    // existing user
                    flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
                    logger.debug(MessageFormat.format("{0} authenticated by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
                    return validateAuthentication(user, AuthenticationType.CONTAINER);
                } else if (settings.getBoolean(Keys.realm.container.autoCreateAccounts, false) && !internalAccount) {
                    // auto-create user from an authenticated container principal
                    user = new UserModel(username.toLowerCase());
                    user.displayName = username;
                    user.password = Constants.EXTERNAL_ACCOUNT;
                    user.accountType = AccountType.CONTAINER;
                    // Try to extract user's informations for the session
                    // it uses "realm.container.autoAccounts.*" as the attribute name to look for
                    HttpSession session = httpRequest.getSession();
                    String emailAddress = resolveAttribute(session, Keys.realm.container.autoAccounts.emailAddress);
                    if (emailAddress != null) {
                        user.emailAddress = emailAddress;
                    }
                    String displayName = resolveAttribute(session, Keys.realm.container.autoAccounts.displayName);
                    if (displayName != null) {
                        user.displayName = displayName;
                    }
                    String userLocale = resolveAttribute(session, Keys.realm.container.autoAccounts.locale);
                    if (userLocale != null) {
                        user.getPreferences().setLocale(userLocale);
                    }
                    String adminRole = settings.getString(Keys.realm.container.autoAccounts.adminRole, null);
                    if (adminRole != null && !adminRole.isEmpty()) {
                        if (httpRequest.isUserInRole(adminRole)) {
                            user.canAdmin = true;
                        }
                    }
                    userManager.updateUserModel(user);
                    flagRequest(httpRequest, AuthenticationType.CONTAINER, user.username);
                    logger.debug(MessageFormat.format("{0} authenticated and created by servlet container principal from {1}", user.username, httpRequest.getRemoteAddr()));
                    return validateAuthentication(user, AuthenticationType.CONTAINER);
                } else if (!internalAccount) {
                    logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}", principal.getName(), httpRequest.getRemoteAddr()));
                }
            }
        }
    }
    // try to authenticate by certificate
    boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
    String[] oids = settings.getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
    UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
    if (model != null) {
        // grab real user model and preserve certificate serial number
        UserModel user = userManager.getUserModel(model.username);
        X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
        if (user != null) {
            flagRequest(httpRequest, AuthenticationType.CERTIFICATE, user.username);
            logger.debug(MessageFormat.format("{0} authenticated by client certificate {1} from {2}", user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
            return validateAuthentication(user, AuthenticationType.CERTIFICATE);
        } else {
            logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}", model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
        }
    }
    if (requiresCertificate) {
        // caller requires client certificate authentication (e.g. git servlet)
        return null;
    }
    UserModel user = null;
    // try to authenticate by cookie
    String cookie = getCookie(httpRequest);
    if (!StringUtils.isEmpty(cookie)) {
        user = userManager.getUserModel(cookie.toCharArray());
        if (user != null) {
            flagRequest(httpRequest, AuthenticationType.COOKIE, user.username);
            logger.debug(MessageFormat.format("{0} authenticated by cookie from {1}", user.username, httpRequest.getRemoteAddr()));
            return validateAuthentication(user, AuthenticationType.COOKIE);
        }
    }
    // try to authenticate by BASIC
    final String authorization = httpRequest.getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Basic")) {
        // Authorization: Basic base64credentials
        String base64Credentials = authorization.substring("Basic".length()).trim();
        String credentials = new String(Base64.decode(base64Credentials), Charset.forName("UTF-8"));
        // credentials = username:password
        final String[] values = credentials.split(":", 2);
        if (values.length == 2) {
            String username = values[0];
            char[] password = values[1].toCharArray();
            user = authenticate(username, password, httpRequest.getRemoteAddr());
            if (user != null) {
                flagRequest(httpRequest, AuthenticationType.CREDENTIALS, user.username);
                logger.debug(MessageFormat.format("{0} authenticated by BASIC request header from {1}", user.username, httpRequest.getRemoteAddr()));
                return validateAuthentication(user, AuthenticationType.CREDENTIALS);
            }
        }
    }
    // Check each configured AuthenticationProvider
    for (AuthenticationProvider ap : authenticationProviders) {
        UserModel authedUser = ap.authenticate(httpRequest);
        if (null != authedUser) {
            flagRequest(httpRequest, ap.getAuthenticationType(), authedUser.username);
            logger.debug(MessageFormat.format("{0} authenticated by {1} from {2} for {3}", authedUser.username, ap.getServiceName(), httpRequest.getRemoteAddr(), httpRequest.getPathInfo()));
            return validateAuthentication(authedUser, ap.getAuthenticationType());
        }
    }
    return null;
}
Also used : UserModel(com.gitblit.models.UserModel) HttpSession(javax.servlet.http.HttpSession) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) UsernamePasswordAuthenticationProvider(com.gitblit.auth.AuthenticationProvider.UsernamePasswordAuthenticationProvider) AuthenticationProvider(com.gitblit.auth.AuthenticationProvider) Principal(java.security.Principal)

Example 83 with Principal

use of java.security.Principal in project hibernate-orm by hibernate.

the class StandardJaccServiceImpl method doPermissionCheckInContext.

private void doPermissionCheckInContext(PermissionCheckEntityInformation entityInformation, PermissibleAction action) {
    final Policy policy = Policy.getPolicy();
    final Principal[] principals = getCallerPrincipals();
    final CodeSource codeSource = entityInformation.getEntity().getClass().getProtectionDomain().getCodeSource();
    final ProtectionDomain pd = new ProtectionDomain(codeSource, null, null, principals);
    // the action is known as 'method name' in JACC
    final EJBMethodPermission jaccPermission = new EJBMethodPermission(entityInformation.getEntityName(), action.getImpliedActions()[0], null, null);
    if (!policy.implies(pd, jaccPermission)) {
        throw new SecurityException(String.format("JACC denied permission to [%s.%s] for [%s]", entityInformation.getEntityName(), action.getImpliedActions()[0], join(principals)));
    }
}
Also used : Policy(java.security.Policy) ProtectionDomain(java.security.ProtectionDomain) CodeSource(java.security.CodeSource) EJBMethodPermission(javax.security.jacc.EJBMethodPermission) Principal(java.security.Principal)

Example 84 with Principal

use of java.security.Principal in project jaggery by wso2.

the class RequestHostObject method jsFunction_getUser.

public static String jsFunction_getUser(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "getUser";
    int argsCount = args.length;
    if (argsCount != 0) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    RequestHostObject rho = (RequestHostObject) thisObj;
    Principal principle = rho.request.getUserPrincipal();
    if (principle == null) {
        return null;
    }
    return principle.getName();
}
Also used : Principal(java.security.Principal)

Example 85 with Principal

use of java.security.Principal in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method engineGetCertificateChain.

public Certificate[] engineGetCertificateChain(String alias) {
    if (alias == null) {
        throw new IllegalArgumentException("null alias passed to getCertificateChain.");
    }
    if (!engineIsKeyEntry(alias)) {
        return null;
    }
    Certificate c = engineGetCertificate(alias);
    if (c != null) {
        Vector cs = new Vector();
        while (c != null) {
            X509Certificate x509c = (X509Certificate) c;
            Certificate nextC = null;
            byte[] bytes = x509c.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (bytes != null) {
                try {
                    ASN1InputStream aIn = new ASN1InputStream(bytes);
                    byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
                    aIn = new ASN1InputStream(authBytes);
                    AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) aIn.readObject());
                    if (id.getKeyIdentifier() != null) {
                        nextC = (Certificate) chainCerts.get(new CertId(id.getKeyIdentifier()));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e.toString());
                }
            }
            if (nextC == null) {
                //
                // no authority key id, try the Issuer DN
                //
                Principal i = x509c.getIssuerDN();
                Principal s = x509c.getSubjectDN();
                if (!i.equals(s)) {
                    Enumeration e = chainCerts.keys();
                    while (e.hasMoreElements()) {
                        X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
                        Principal sub = crt.getSubjectDN();
                        if (sub.equals(i)) {
                            try {
                                x509c.verify(crt.getPublicKey());
                                nextC = crt;
                                break;
                            } catch (Exception ex) {
                            // continue
                            }
                        }
                    }
                }
            }
            cs.addElement(c);
            if (// self signed - end of the chain
            nextC != c) {
                c = nextC;
            } else {
                c = null;
            }
        }
        Certificate[] certChain = new Certificate[cs.size()];
        for (int i = 0; i != certChain.length; i++) {
            certChain[i] = (Certificate) cs.elementAt(i);
        }
        return certChain;
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

Principal (java.security.Principal)931 Test (org.junit.Test)243 Subject (javax.security.auth.Subject)114 EveryonePrincipal (org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal)114 HashSet (java.util.HashSet)89 User (org.apache.jackrabbit.api.security.user.User)75 Group (org.apache.jackrabbit.api.security.user.Group)74 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)58 Privilege (javax.jcr.security.Privilege)57 RepositoryException (javax.jcr.RepositoryException)51 IOException (java.io.IOException)50 ArrayList (java.util.ArrayList)48 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 TestPrincipal (org.apache.jackrabbit.core.security.TestPrincipal)45 AbstractSecurityTest (org.apache.jackrabbit.oak.AbstractSecurityTest)43 EveryonePrincipal (org.apache.jackrabbit.core.security.principal.EveryonePrincipal)42 PrincipalIterator (org.apache.jackrabbit.api.security.principal.PrincipalIterator)40 HashMap (java.util.HashMap)39 PrincipalImpl (org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl)39 X500Principal (javax.security.auth.x500.X500Principal)38