Example usage for java.security Principal Principal

List of usage examples for java.security Principal Principal

Introduction

In this page you can find the example usage for java.security Principal Principal.

Prototype

Principal

Source Link

Usage

From source file:org.apache.qpid.server.security.auth.sasl.CRAMMD5HexServerTest.java

private Principal createTestPrincipal(final String name) {
    return new Principal() {
        public String getName() {
            return name;
        }/*from  www . j  a  v a2s .  c  om*/
    };
}

From source file:org.apache.rahas.test.util.TestUtil.java

private static void populateReceivedResults(MessageContext messageContext) throws Exception {
    List<WSSecurityEngineResult> wsSecEngineResults = new ArrayList<WSSecurityEngineResult>();
    WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.SIGN);

    Principal principal = new Principal() {
        public String getName() {
            return "apache";
        }/*w w  w . j a  va 2 s.  c  o m*/
    };

    result.put(WSSecurityEngineResult.TAG_PRINCIPAL, principal);
    result.put(WSSecurityEngineResult.TAG_X509_CERTIFICATE, getDefaultCertificate());

    wsSecEngineResults.add(result);

    WSHandlerResult handlerResult = new WSHandlerResult(null, wsSecEngineResults);

    List<WSHandlerResult> handlerResultList = new ArrayList<WSHandlerResult>();
    handlerResultList.add(handlerResult);

    messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResultList);

}

From source file:org.apache.wicket.protocol.http.mock.MockHttpServletRequest.java

/**
 * Get the user principal.//www  . ja v a2 s . c  om
 * 
 * @return A user principal
 */
@Override
public Principal getUserPrincipal() {
    final String user = getRemoteUser();
    if (user == null) {
        return null;
    } else {
        return new Principal() {
            @Override
            public String getName() {
                return user;
            }
        };
    }
}

From source file:org.codice.ddf.security.handler.anonymous.AnonymousHandler.java

/**
 * Extracts a Principal from a UsernameToken
 *
 * @param result/* w ww . ja  va2s .c o m*/
 * @return Principal
 */
private Principal getPrincipal(final UsernameTokenType result) {
    return new Principal() {
        private String username = result.getUsername().getValue();

        @Override
        public String getName() {
            return username;
        }
    };
}

From source file:org.forgerock.openam.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * If Jwt is invalid then throws LoginException, otherwise Jwt is valid and the realm is check to ensure
 * the user is authenticating in the same realm.
 *
 * @param messageInfo {@inheritDoc}/*w  ww  . j  a  v  a  2s . co m*/
 * @param clientSubject {@inheritDoc}
 * @param callbacks {@inheritDoc}
 * @return {@inheritDoc}
 * @throws LoginException {@inheritDoc}
 */
@Override
protected boolean process(MessageInfo messageInfo, Subject clientSubject, Callback[] callbacks)
        throws LoginException {

    Jwt jwt = getServerAuthModule()
            .validateJwtSessionCookie(prepareMessageInfo(getHttpServletRequest(), getHttpServletResponse()));

    if (jwt == null) {
        //BAD
        throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "cookieNotValid", null);
    } else {
        //GOOD
        Map<String, Object> claimsSetContext = jwt.getClaimsSet().getClaim(AuthNFilter.ATTRIBUTE_AUTH_CONTEXT,
                Map.class);
        if (claimsSetContext == null) {
            throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "jaspiContextNotFound", null);
        }

        // Need to check realm
        String jwtRealm = (String) claimsSetContext.get(OPENAM_REALM_CLAIM_KEY);
        if (!getRequestOrg().equals(jwtRealm)) {
            throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "authFailedDiffRealm", null);
        }

        // Need to get user from jwt to use in Principal
        final String username = (String) claimsSetContext.get(OPENAM_USER_CLAIM_KEY);
        principal = new Principal() {
            public String getName() {
                return username;
            }
        };

        setUserSessionProperty(JwtSessionModule.JWT_VALIDATED_KEY, Boolean.TRUE.toString());
        return true;
    }
}

From source file:org.forgerock.openidm.jaspi.modules.IDMUserAuthModule.java

/**
 * Validates the request by authenticating against either the client certificate in the request, internally or
 * Basic Authentication from the request header internally.
 *
 * @param messageInfo {@inheritDoc}/*w w  w  .j  ava  2s.  c  om*/
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) {

    HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
    boolean authenticated;

    final String headerLogin = req.getHeader(HEADER_USERNAME);
    String basicAuth = req.getHeader("Authorization");
    // if we see the certificate port this request is for client auth only
    if (allowClientCertOnly(req)) {
        authenticated = authenticateUsingClientCert(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (headerLogin != null) {
        authenticated = authenticateUser(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (basicAuth != null) {
        authenticated = authenticateUsingBasicAuth(basicAuth, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else {
        //Auth failure will be logged in IDMServerAuthModule super type.
        return AuthStatus.SEND_FAILURE;
    }
    authData.setResource(queryOnResource);
    logger.debug("Found valid session for {} id {} with roles {}", authData.getUsername(), authData.getUserId(),
            authData.getRoles());

    if (authenticated) {
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return headerLogin;
            }
        });
    }

    return authenticated ? AuthStatus.SUCCESS : AuthStatus.SEND_FAILURE;
}

From source file:org.forgerock.openidm.jaspi.modules.PassthroughModule.java

/**
 * Validates the client's request by passing through the request to be authenticated against a OpenICF Connector.
 *
 * @param messageInfo {@inheritDoc}/* w ww  .  java2  s .c om*/
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException If there is a problem performing the authentication.
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) throws AuthException {

    LOGGER.debug("PassthroughModule: validateRequest START");

    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();

    try {
        LOGGER.debug("PassthroughModule: Delegating call to internal AuthFilter");
        //Set pass through auth resource on request so can be accessed by authnPopulateContext.js script.
        setPassThroughAuthOnRequest(messageInfo);

        final String username = request.getHeader("X-OpenIDM-Username");
        String password = request.getHeader("X-OpenIDM-Password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            LOGGER.debug("Failed authentication, missing or empty headers");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }

        authData.setUsername(username);
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return username;
            }
        });
        boolean authenticated = passthroughAuthenticator.authenticate(authData, password);

        if (authenticated) {
            LOGGER.debug("PassthroughModule: Authentication successful");
            LOGGER.debug("Found valid session for {} id {} with roles {}", authData.getUsername(),
                    authData.getUserId(), authData.getRoles());

            //Auth success will be logged in IDMServerAuthModule super type.
            return AuthStatus.SUCCESS;
        } else {
            LOGGER.debug("PassthroughModule: Authentication failed");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }
    } finally {
        LOGGER.debug("PassthroughModule: validateRequest END");
    }
}

From source file:org.forgerock.tinker.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * If Jwt is invalid then throws LoginException, otherwise Jwt is valid and the realm is check to ensure
 * the user is authenticating in the same realm.
 *
 * @param messageInfo {@inheritDoc}/*from w  w w .  ja v  a 2 s.c  om*/
 * @param clientSubject {@inheritDoc}
 * @param callbacks {@inheritDoc}
 * @return {@inheritDoc}
 * @throws LoginException {@inheritDoc}
 */
@Override
protected boolean process(MessageInfo messageInfo, Subject clientSubject, Callback[] callbacks)
        throws LoginException {

    DEBUG.message("TINKER: PersistentCookieAuthenticationModule.process() - 2.");
    final Jwt jwt = getServerAuthModule().validateJwtSessionCookie(messageInfo);

    if (jwt == null) {
        //BAD
        // Change Start : Output data to message debug
        DEBUG.message("TINKER: PersistentCookieAuthenticationModule.process().");
        DEBUG.message("COOKIE is BAD.");
        // Change End
        throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "cookieNotValid", null);
    } else {
        //GOOD
        DEBUG.message("TINKER: PersistentCookieAuthenticationModule.process().");
        DEBUG.message("COOKIE is GOOD.");

        final Map<String, Object> claimsSetContext = jwt.getClaimsSet()
                .getClaim(JaspiRuntime.ATTRIBUTE_AUTH_CONTEXT, Map.class);
        if (claimsSetContext == null) {
            throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "jaspiContextNotFound", null);
        }

        // Need to check realm
        final String jwtRealm = (String) claimsSetContext.get(OPENAM_REALM_CLAIM_KEY);
        if (!getRequestOrg().equals(jwtRealm)) {
            throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "authFailedDiffRealm", null);
        }

        final String storedClientIP = (String) claimsSetContext.get(OPENAM_CLIENT_IP_CLAIM_KEY);
        if (enforceClientIP) {
            enforceClientIP(storedClientIP);
        }

        // Need to get user from jwt to use in Principal
        final String username = (String) claimsSetContext.get(OPENAM_USER_CLAIM_KEY);
        principal = new Principal() {
            public String getName() {
                return username;
            }
        };

        setUserSessionProperty(JwtSessionModule.JWT_VALIDATED_KEY, Boolean.TRUE.toString());

        // Change Start : Output data to message debug

        JwtClaimsSet claimsSet = jwt.getClaimsSet();
        DEBUG.message("TINKER: PersistentCookieAuthenticationModule.process().");
        DEBUG.message("COOKIE is GOOD.");
        DEBUG.message("username=" + username);
        DEBUG.message("realm=" + jwtRealm);
        DEBUG.message("jwt.getPrincipal()=" + claimsSet.getPrincipal());
        DEBUG.message("jwt.getIssuer()=" + claimsSet.getIssuer());
        DEBUG.message("jwt.getNotBeforeTime()=" + claimsSet.getNotBeforeTime().toString());
        DEBUG.message("jwt.getExpirationTime()=" + claimsSet.getExpirationTime().toString());
        DEBUG.message("jwt.getIssuedAtTime()=" + claimsSet.getIssuedAtTime().toString());
        // Change End

        return true;
    }
}

From source file:org.liveSense.service.securityManager.SecurityManagerServiceImpl.java

/** {@inheritDoc} */
@Override//from w  ww.  j  a v a 2  s  .c  o  m
public Group addGroup(Session session, final String groupName, Map<String, Object> properties)
        throws GroupAlreadyExistsException, InternalException {
    Group group = null;
    try {

        UserManager userManager = AccessControlUtil.getUserManager(session);
        Authorizable authorizable = userManager.getAuthorizable(groupName);

        if (authorizable != null) {
            // Principal already exists!
            throw new GroupAlreadyExistsException(
                    "A principal already exists with the requested name: " + groupName);
        }

        group = userManager.createGroup(new Principal() {

            @Override
            public String getName() {
                return groupName;
            }
        });

        if (properties != null) {
            for (Object key : properties.keySet()) {
                if (properties.get(key) != null) {
                    GenericValue val = GenericValue.getGenericValueFromObject(properties.get(key));
                    if (val.isMultiValue()) {
                        group.setProperty((String) key, val.getValues());
                    } else {
                        group.setProperty((String) key, val.get());
                    }
                }
            }
        }

    } catch (IllegalArgumentException ex) {
        throw new InternalException(ex);
    } catch (RepositoryException ex) {
        throw new InternalException("Repository exception", ex);
    } finally {
    }
    return group;
}

From source file:org.polymap.rhei.um.auth.UmAuthorizationModule.java

@Override
public Set<Principal> rolesOf(Subject subject) {
    Set<UserPrincipal> principals = subject.getPrincipals(UserPrincipal.class);
    UserPrincipal principal = Iterables.getOnlyElement(principals);

    Set<Principal> result = new HashSet();
    if (principal.getName().equals("admin")) {
        ////from  ww  w .j  a va2s  .  c  om
    } else {
        User user = ((UmUserPrincipal) principal).getUser();
        for (final String groupName : loginModule.repo.groupsOf(user)) {
            result.add(new Principal() {
                @Override
                public String getName() {
                    return groupName;
                }
            });
        }
    }
    return result;
}