Example usage for javax.security.auth.login LoginContext login

List of usage examples for javax.security.auth.login LoginContext login

Introduction

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

Prototype

public void login() throws LoginException 

Source Link

Document

Perform the authentication.

Usage

From source file:be.fedict.hsm.ws.impl.JAASSOAPHandler.java

private void login(SOAPMessageContext context) throws LoginException, CertificateEncodingException {
    X509Certificate certificate = WSSecuritySOAPHandler.getAuthenticatedCertificate(context);
    byte[] encodedCertificate = certificate.getEncoded();
    NamePasswordCallbackHandler usernamePasswordHandler = new NamePasswordCallbackHandler(encodedCertificate);
    LoginContext loginContext = new LoginContext(ApplicationClientSecurityDomain.NAME, usernamePasswordHandler);
    context.put(LOGIN_CONTEXT_ATTRIBUTE, loginContext);
    loginContext.login();
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}//from   w  w  w .  ja v a2s .c o  m
 */
public Subject login(final UserCredential pUserCredential) {
    try {
        final CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(pUserCredential);
        final LoginContext loginContext = new LoginContext(mLoginModuleName, callbackHandler);
        loginContext.login();
        final Subject subject = loginContext.getSubject();
        if (mStateManager != null && subject != null) {
            final RequestState requestState = new RequestState();
            requestState.setStateId(pUserCredential.getStateId());
            requestState.setSubject(subject);
            requestState.setUserName(pUserCredential.getUser());
            mStateManager.addRequestStateForToken(pUserCredential.getStateId(), requestState);
        }
        return subject;
    } catch (LoginException e) {
        throw new ServiceException(pUserCredential,
                "Failed to authenticate an user with the credentials - " + pUserCredential, e);
    }
}

From source file:com.redhat.tools.kerberos.SunJaasKerberosTicketValidator.java

public void setProperties() throws Exception {
    // if (keyTabLocation instanceof ClassPathResource) {
    // LOG.warn("Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
    // }/*from w  w  w.j a v a  2  s . co  m*/
    URL keytabURL = new URL(this.keyTabLocation);
    LoginConfig loginConfig = new LoginConfig(keytabURL.toExternalForm(), this.servicePrincipal, this.debug);
    Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    LoginContext lc = new LoginContext("", sub, null, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}

From source file:com.redhat.tools.kerberos.SunJaasKerberosClient.java

public String login(String username, String password) {
    LOG.debug("Trying to authenticate " + username + " with Kerberos");
    String validatedUsername = "";

    try {//  ww w.j a  v a 2s.c  om
        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        validatedUsername = loginContext.getSubject().getPrincipals().iterator().next().toString();
        loginContext.logout();
    } catch (LoginException e) {
        e.printStackTrace();
    }
    return validatedUsername;

}

From source file:net.sf.jpam.jaas.LoginContextTest.java

/**
 * Checks that we can login./*from   www  .j av  a 2s  .co  m*/
 * <p/>
 * In this test, login is successful and commit is called.
 * @throws LoginException
 */
public void testLoginContext() throws LoginException {
    LoginContext loginContext;
    loginContext = new LoginContext("net-sf-jpam", new JpamCallbackHandler());
    loginContext.login();
}

From source file:org.jasig.cas.authentication.handler.support.JaasAuthenticationHandler.java

protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials)
        throws AuthenticationException {

    final String transformedUsername = getPrincipalNameTransformer().transform(credentials.getUsername());

    try {//from   w  ww.ja  v a 2  s  .  co m
        if (log.isDebugEnabled()) {
            log.debug("Attempting authentication for: " + transformedUsername);
        }
        final LoginContext lc = new LoginContext(this.realm,
                new UsernamePasswordCallbackHandler(transformedUsername, credentials.getPassword()));

        lc.login();
        lc.logout();
    } catch (final LoginException fle) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed for: " + transformedUsername);
        }
        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Authentication succeeded for: " + transformedUsername);
    }
    return true;
}

From source file:org.apache.nifi.hadoop.KerberosKeytabSPNegoScheme.java

@Override
public byte[] generateToken(byte[] input, String authServer, Credentials credentials) {
    Set<Principal> principals = new HashSet<>();
    principals.add(credentials.getUserPrincipal());
    Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());

    try {//from w  w  w .  j  a  v a2s .c om
        LoginContext loginContext = new LoginContext("", subject, null,
                new KerberosConfiguration(credentials.getUserPrincipal().getName(),
                        ((KerberosKeytabCredentials) credentials).getKeytab()));
        loginContext.login();
        Subject loggedInSubject = loginContext.getSubject();

        return Subject.doAs(loggedInSubject, new PrivilegedExceptionAction<byte[]>() {

            public byte[] run() throws UnknownHostException, ClassNotFoundException, GSSException,
                    IllegalAccessException, NoSuchFieldException {
                GSSManager gssManager = GSSManager.getInstance();
                String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", authServer);
                Oid serviceOid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, serviceOid);
                Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                GSSContext gssContext = gssManager.createContext(serviceName, mechOid, null, 0);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);
                return gssContext.initSecContext(input, 0, input.length);
            }

        });
    } catch (PrivilegedActionException | LoginException e) {
        throw new RuntimeException(e);
    }
}

From source file:freeipa.client.JSONRequestServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String jsonRequest = req.getParameter("json");
    URL ipaUrl = new URL("https://vm-144.idm.lab.eng.brq.redhat.com/ipa/json");
    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("  <head>");
    writer.println("    <title>Json request servlet</title>");
    writer.println("  </head>");
    writer.println("  <body>");
    writer.println("    <h1>JSON POST Test:</h1>");

    displayForm(writer);/*from  w  ww  .ja v  a  2  s. c o  m*/
    if (jsonRequest == null) {
        try {
            LoginContext context = new LoginContext(SECURITY_DOMAIN);
            log.debug("Obtained LoginContext for '" + SECURITY_DOMAIN + "' security-domain.");

            context.login();
            writer.println("<h4>Authenticated</h4>");

            Subject subject = context.getSubject();
            KerberosHttpClient.makeCallWithKerberosAuthn(ipaUrl, subject, httpClient);
        } catch (Exception e) {
            // TODO - Output full exception detail.
            writer.println("<h5>Failed!</h5>");
            writer.print("<p>");
            writer.print(e.getClass().getName());
            writer.print(" - ");
            writer.print(e.getMessage());
            writer.println("</p>");

            log.error("testDomain Failed", e);
        }
    } else {
        testRequest(jsonRequest, writer);
    }

    writer.println("  </body>");
    writer.println("</html>");
    writer.flush();
}

From source file:com.srotya.collectd.storm.StormNimbusMetrics.java

public void login() {
    try {//  www.ja va2  s.co  m
        LoginContext ctx = new LoginContext("KrbLogin");
        ctx.login();
        subject = ctx.getSubject();
        Collectd.logDebug("Logged in");
    } catch (LoginException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:net.sf.jpam.jaas.LoginContextTest.java

/**
 * Checks what happens if a bad password is given
 * <p/>/*from  w w  w  .  j  a  v  a  2s.  c om*/
 * In this test, login is unsuccessful and abort is called.
 * @throws LoginException
 */
public void testLoginContextBadPassword() throws LoginException {
    LoginContext loginContext;
    callbackCredentials = user1BadCredentials;
    loginContext = new LoginContext("net-sf-jpam", new JpamCallbackHandler());
    try {
        loginContext.login();
        fail();
    } catch (FailedLoginException e) {
        //
    }
}