Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.josso.agent.http.JOSSOSecurityContext.java

/**
 * Creates a new security context for the given subject.  The subject must contain at least one SSOUser principal instance.
 *//*from w  w w  . j  a v a 2 s  .  c  o m*/
public JOSSOSecurityContext(Subject subject) {

    Set principals = subject.getPrincipals();
    roles = new HashMap();

    for (Iterator it = principals.iterator(); it.hasNext();) {

        Principal p = (Principal) it.next();
        if (p instanceof SSOUser) {
            if (ssoUser != null)
                throw new IllegalArgumentException("Subject cannot contain multiple SSOUser instances");
            this.ssoUser = (SSOUser) p;
        } else if (p instanceof SSORole) {
            SSORole r = (SSORole) p;
            roles.put(r.getName(), r);
        }

    }

    if (ssoUser == null)
        throw new IllegalArgumentException("No SSOUser principal found in subject");

}

From source file:org.josso.liferay5.agent.LiferayNativeSSOAgent.java

/**
 * Resolves an authentication request directly against the gateway.
 *
 * @param request containing the SSO Session id.
 * @return null if no principal can be authenticated using the received SSO Session Id
 *//*  ww w  .j a  va  2  s.  c  om*/
protected Principal authenticate(SSOAgentRequest request) {

    String ssoSessionId = request.getSessionId();

    Principal ssoUser = super.authenticate(request);
    if (ssoUser != null) {
        Subject subject = new Subject();
        subject.getPrincipals().add(ssoUser);
        SSORole[] ssoRolePrincipals = getRoleSets(request.getRequester(), ssoSessionId, request.getNodeId());
        for (int i = 0; i < ssoRolePrincipals.length; i++) {
            subject.getPrincipals().add(ssoRolePrincipals[i]);
            log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
        }
        LiferaySSOAgentRequest r = (LiferaySSOAgentRequest) request;
        JOSSOSecurityContext ctx = new JOSSOSecurityContext(subject);
        r.setSecurityContext(ctx);
    }

    return ssoUser;
}

From source file:org.josso.servlet.agent.GenericServletNativeSSOAgent.java

/**
 * Resolves an authentication request directly against the gateway.
 * /* w  w w  .j a va2 s  . c  o m*/
 * @param request containing the SSO Session id.
 * @return null if no principal can be authenticated using the received SSO Session Id
 */
protected Principal authenticate(SSOAgentRequest request) {

    String ssoSessionId = request.getSessionId();

    Principal ssoUser = super.authenticate(request);
    if (ssoUser != null) {
        Subject subject = new Subject();
        subject.getPrincipals().add(ssoUser);
        SSORole[] ssoRolePrincipals = getRoleSets(request.getRequester(), ssoSessionId, request.getNodeId());
        for (int i = 0; i < ssoRolePrincipals.length; i++) {
            subject.getPrincipals().add(ssoRolePrincipals[i]);
            log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
        }
        GenericServletSSOAgentRequest r = (GenericServletSSOAgentRequest) request;
        JOSSOSecurityContext ctx = new JOSSOSecurityContext(subject);
        ctx.setSSOSession(ssoSessionId);
        r.setSecurityContext(ctx);
    }

    return ssoUser;
}

From source file:uk.org.openeyes.oink.security.SimpleIdentityService.java

@Override
public String getOrganisation(Subject s) {
    if (s == null) {
        return null;
    }//from w  w w  .j a va  2s. com

    for (Principal p : s.getPrincipals()) {
        if (p instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken details = (UsernamePasswordAuthenticationToken) p;
            String name = details.getName();
            String[] parts = name.split("@");
            if (parts.length == 2) {
                return parts[1];
            }
        }
    }
    return null;
}

From source file:fi.okm.mpass.idp.authn.impl.AbstractIdentity.java

/**
 * Returns user Subject based on key and profile.
 * //  w ww.  ja va2  s .  c  om
 * @param key
 *            Connection Key of the user
 * @param profile
 *            Profile of the user
 * @return User Subject
 */
public Subject getSubject(ConnectionKey key, UserProfile profile) {
    log.trace("Entering");
    Subject subject = new Subject();
    String userId = key.getProviderUserId();
    subject.getPrincipals().add(new UsernamePrincipal(userId));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.userId, userId));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.providerId, key.getProviderId()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.email, profile.getEmail()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.firstName, profile.getFirstName()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.lastName, profile.getLastName()));
    log.trace("Leaving");
    return subject;

}

From source file:org.apache.coheigea.cxf.syncope.authorization.SyncopeRolesInterceptor.java

public void handleMessage(Message message) throws Fault {
    SecurityContext context = message.get(SecurityContext.class);
    if (context == null) {
        return;//from  w  w  w.  j  a  v  a  2  s .c  o  m
    }
    Principal principal = context.getUserPrincipal();
    UsernameToken usernameToken = (UsernameToken) message.get(SecurityToken.class);
    if (principal == null || usernameToken == null || !principal.getName().equals(usernameToken.getName())) {
        return;
    }

    // Read the user from Syncope and get the roles
    WebClient client = WebClient.create(address, Collections.singletonList(new JacksonJsonProvider()));

    String authorizationHeader = "Basic "
            + Base64Utility.encode((usernameToken.getName() + ":" + usernameToken.getPassword()).getBytes());

    client.header("Authorization", authorizationHeader);

    client = client.path("users/self");
    UserTO user = null;
    try {
        user = client.get(UserTO.class);
        if (user == null) {
            Exception exception = new Exception("Authentication failed");
            throw new Fault(exception);
        }
    } catch (RuntimeException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new Fault(ex);
    }

    // Now get the roles
    List<MembershipTO> membershipList = user.getMemberships();
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    for (MembershipTO membership : membershipList) {
        String roleName = membership.getGroupName();
        subject.getPrincipals().add(new SimpleGroup(roleName, usernameToken.getName()));
    }
    subject.setReadOnly();

    message.put(SecurityContext.class, new DefaultSecurityContext(principal, subject));
}

From source file:org.tolven.restful.UserFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();
    //      LoginContext loginContext = (LoginContext) session.getAttribute("loginContext");
    Principal principal = request.getUserPrincipal();
    // If we have a principal, then we can proceed
    if (principal != null) {
        chain.doFilter(servletRequest, servletResponse);
        return;/*from  ww  w  . j av a2  s.  co  m*/
    }
    // before we accept a password, must ensure that this is a secure session
    if (!request.isSecure()) {
        response.setStatus(403);
        return;
    }
    String authorizationHeader = request.getHeader("Authorization");
    // See if we have the username/password
    if (authorizationHeader != null && authorizationHeader.startsWith("Basic ")) {
        Base64 decoder = new Base64();
        byte[] decoded = decoder.decode(authorizationHeader.substring(6).getBytes());
        String[] usernamePassword = new String(decoded).split(":");
        //WebAuthentication webA = new WebAuthentication();
        //boolean loginStatus = webA.login(usernamePassword[0], usernamePassword[1]);
        //if (!loginStatus) {
        //   response.setStatus(403);
        //   System.out.println( "Login for " + usernamePassword[0] + " - failed");
        //   return;
        //}
        System.out.println("Login for " + usernamePassword[0] + " - succeeded");
        //principal = new TolvenPrincipal(usernamePassword[0]);
        Subject subject = new Subject();
        subject.getPrincipals().add(principal);
        //            loginContext = new LoginContext("tolvenLDAP", subject, new CB(usernamePassword[0], usernamePassword[1].toCharArray()));
        //            loginContext.login();
        // Success
        //         session.setAttribute("loginContext", loginContext);
        chain.doFilter(servletRequest, servletResponse);
    } else {
        // Ask for password now
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"tolvenLDAP\"");
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.ShibbolethSSOTestCase.java

protected ShibbolethSSOLoginContext buildLoginContext() {
    Principal principal = new UsernamePrincipal("test");

    Subject subject = new Subject();
    subject.getPrincipals().add(principal);

    AuthenticationMethodInformation authnInfo = new AuthenticationMethodInformationImpl(subject, principal,
            "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified", new DateTime(), 3600);

    ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
    loginContext.setAuthenticationMethodInformation(authnInfo);
    loginContext.setPrincipalAuthenticated(true);
    loginContext.setRelyingParty("urn:example.org:sp1");
    loginContext.setSpAssertionConsumerService("https://example.org/mySP");
    loginContext.setSpTarget("https://example.org/mySP");

    return loginContext;
}

From source file:fi.okm.mpass.idp.authn.impl.SocialUserAuthServletTest.java

protected SocialRedirectAuthenticator initSubjectAuthenticator() throws Exception {
    SocialRedirectAuthenticator authenticator = Mockito.mock(SocialRedirectAuthenticator.class);
    Subject subject = new Subject();
    subject.getPrincipals().add(new UsernamePrincipal(username));
    Mockito.when(authenticator.getSubject((HttpServletRequest) Mockito.any())).thenReturn(subject);
    return authenticator;
}

From source file:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java

public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }/*from w w  w.j  a  v  a 2  s . c o m*/

    // Validate the UsernameToken
    UsernameToken usernameToken = credential.getUsernametoken();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }
    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - digest passwords are not accepted");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (usernameToken.getPassword() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - no password was provided");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    // Validate it via Spring Security

    // Set a Subject up
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            usernameToken.getName(), usernameToken.getPassword());
    Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    Set<Authentication> authentications = subject.getPrincipals(Authentication.class);
    Authentication authenticated = null;
    try {
        authenticated = authenticationManager.authenticate(authentications.iterator().next());
    } catch (AuthenticationException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    if (!authenticated.isAuthenticated()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    for (GrantedAuthority authz : authenticated.getAuthorities()) {
        System.out.println("Granted: " + authz.getAuthority());
    }

    // Authorize request
    if (accessDecisionManager != null && !requiredRoles.isEmpty()) {
        List<ConfigAttribute> attributes = SecurityConfig
                .createList(requiredRoles.toArray(new String[requiredRoles.size()]));
        for (ConfigAttribute attr : attributes) {
            System.out.println("Attr: " + attr.getAttribute());
        }
        accessDecisionManager.decide(authenticated, this, attributes);
    }

    credential.setSubject(subject);
    return credential;
}