Example usage for javax.security.auth Subject Subject

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

Introduction

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

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:org.apache.hadoop.security.SecureClientLogin.java

public synchronized static Subject login(String user) throws IOException {
    Subject subject = new Subject();
    subject.getPrincipals().add(new User(user));
    return 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
 *///from  www.  j  a va 2s .  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.
 * // www .  j  av a  2  s  .co  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:org.apache.servicemix.http.jetty.JaasUserRealm.java

public Principal authenticate(final String username, final Object credentials, Request request) {
    try {/*w  w  w .ja va2 s . co m*/
        if ((username != null) && (!username.equals(""))) {

            JaasJettyPrincipal userPrincipal = userMap.get(username);

            // user has been previously authenticated, but
            // re-authentication has been requested, so remove them
            if (userPrincipal != null) {
                userMap.remove(username);
            }

            // set up the login context
            Subject subject = new Subject();
            authenticationService.authenticate(subject, domain, username, credentials);
            // login success
            userPrincipal = new JaasJettyPrincipal(username);
            userPrincipal.setSubject(subject);

            userMap.put(username, userPrincipal);

            return userPrincipal;
        } else {
            LOG.debug("Login Failed - null userID");
            return null;
        }

    } catch (GeneralSecurityException e) {
        LOG.debug("Login Failed", e);
        return null;
    }
}

From source file:org.josso.tc50.agent.CatalinaNativeRealm.java

@Override
public Principal authenticate(String username, String credentials) {
    try {/*from w w w .  j a  v  a  2  s.c  o m*/
        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            log.warn("No SSO Agent request found in thread local variable, can't identify requester");

        SSOUser ssoUser = im.findUserInSession(requester, username);

        Principal principal = null;

        if (ssoUser != null) {
            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
            }
            // Return the appropriate Principal for this authenticated Subject
            principal = createPrincipal(username, subject);
        }

        return principal;
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        return null;
    } catch (Exception e) {
        log.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
}

From source file:org.apache.hadoop.io.crypto.tool.kerberos.SpnegoRestCli.java

public StringBuffer getResult() throws Exception {
    AccessControlContext context = AccessController.getContext();
    Subject subject = Subject.getSubject(context);
    if (subject == null) {
        subject = new Subject();
        LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
        login.login();//from   ww w  .  j  av  a2  s .co  m
    }
    Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            sb = new RestClient(url).getResult();
            return null;
        }
    });
    return sb;
}

From source file:net.sourceforge.safr.sample.Sample.java

Subject createSubjectForUser(String userId) {
    User user = userService.findUser(userId);
    Subject subject = new Subject();
    addUserPrincipal(subject, user);/*from  ww w .  j  a  v a 2s  .  co  m*/
    addRolePrincipals(subject, user);
    return subject;
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.KerberosTokenGenerator.java

private void login(final NTUser userName, final String password) throws LoginException {
    this.subject = new Subject();
    LoginContext login;/*w  w w.  j a v a  2s .com*/
    login = new LoginContext("", subject, new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    //We may need some more complete mapping between AD user domain and Kerberos realms  
                    String kerbUserSPN = userName.getUserName();
                    if (StringUtils.isNotBlank(userName.getDomain())) {
                        kerbUserSPN += "@" + userName.getDomain().toUpperCase();
                    }

                    log.debug("Kerberos login name: " + kerbUserSPN);
                    ((NameCallback) callback).setName(kerbUserSPN);
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                }
            }
        }
    }, new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> config = new HashMap<String, String>();
            config.put("useTicketCache", "false");

            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, config) };
        }
    });
    login.login();

}

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  a2s .  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.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

public AstroboaLogin(CallbackHandler callbackHandler, IdentityStore internalIdentityStore,
        RepositoryDao repositoryDao) {/*  w  w w .j  av a2s . co m*/

    this.subject = new Subject();
    this.callbackHandler = callbackHandler;
    this.identity = null;
    this.identityStore = internalIdentityStore;
    this.loggedInPerson = null;
    this.useExternalIdentity = false;
    this.repositoryId = null;
    this.repositoryDao = repositoryDao;

}