Java Code Examples for javax.security.auth.login.LoginException#getMessage()

The following examples show how to use javax.security.auth.login.LoginException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImpalaMetadataTask.java    From envelope with Apache License 2.0 7 votes vote down vote up
@Override
public void configure(Config config) {
  // Merge with defaults
  this.config = config.withFallback(ConfigFactory.parseString(generateDefaultConfig()));

  // Initialize kerberos if required
  if (isKerberos(config)) {
    try {
      loginContext = KerberosUtils.createKerberosLoginContext("envelope-impala-context", config);
    } catch (LoginException e) {
      throw new RuntimeException("Problem creating Kerberos login context: " + e.getMessage());
    }
  }

  // Build JDBC connection string
  connectionString = buildConnectionString();
}
 
Example 2
Source File: AuthHandler.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Login using a username and password only. Creates a session containing the userId
 * and returns the key for the session.
 * @param username Username to check
 * @param password Password to check
 * @param durationIn The session duration
 * @return Returns the key for the session
 * @throws LoginException Throws a LoginException if the user can't be logged in.
 *
 * @xmlrpc.doc Login using a username and password. Returns the session key
 * used by other methods.
 * @xmlrpc.param #param("string", "username")
 * @xmlrpc.param #param("string", "password")
 * @xmlrpc.param #param_desc("int", "duration", "Length of session.")
 * @xmlrpc.returntype
 *     #param("string", "sessionKey")
 */
public String login(String username, String password, Integer durationIn)
                  throws LoginException {
    //Log in the user (handles authentication and active/disabled logic)
    User user = null;
    try {
        user = UserManager.loginReadOnlyUser(username, password);
    }
    catch (LoginException e) {
        // Convert to fault exception
        throw new UserLoginException(e.getMessage());
    }

    long duration = getDuration(durationIn);
    //Create a new session with the user
    WebSession session = SessionManager.makeSession(user.getId(), duration);
    return session.getKey();
}
 
Example 3
Source File: AuthHandler.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Login using a username and password only. Creates a session containing the userId
 * and returns the key for the session.
 * @param username Username to check
 * @param password Password to check
 * @param durationIn The session duration
 * @return Returns the key for the session
 * @throws LoginException Throws a LoginException if the user can't be logged in.
 *
 * @xmlrpc.doc Login using a username and password. Returns the session key
 * used by other methods.
 * @xmlrpc.param #param("string", "username")
 * @xmlrpc.param #param("string", "password")
 * @xmlrpc.param #param_desc("int", "duration", "Length of session.")
 * @xmlrpc.returntype
 *     #param("string", "sessionKey")
 */
public String login(String username, String password, Integer durationIn)
                  throws LoginException {
    //Log in the user (handles authentication and active/disabled logic)
    User user = null;
    try {
        user = UserManager.loginReadOnlyUser(username, password);
    }
    catch (LoginException e) {
        // Convert to fault exception
        throw new UserLoginException(e.getMessage());
    }

    long duration = getDuration(durationIn);
    //Create a new session with the user
    WebSession session = SessionManager.makeSession(user.getId(), duration);
    return session.getKey();
}
 
Example 4
Source File: JAASAuthenticationStrategy.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticate(String name, String password) {
    if (contextName != null) {
        try {
            // Login using JAAS
            CallbackHandler callbackHandler =
                new NamePasswordCallbackHandler(name, password);
            LoginContext ctx = new LoginContext(contextName, null, callbackHandler, loginConfig);
            ctx.login();
            ctx.logout();
            return true;
        } catch (LoginException ex) {
            String errorMessage = "Authentication failed: " + ex.getMessage();
            LOG.log(Level.FINE, errorMessage, ex);
        }
    }
    return false;
}
 
Example 5
Source File: AbstractKerberosUser.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a logout of the current user.
 *
 * @throws LoginException if the logout fails
 */
@Override
public synchronized void logout() throws LoginException {
    if (!isLoggedIn()) {
        return;
    }

    try {
        loginContext.logout();
        loggedIn.set(false);
        LOGGER.debug("Successful logout for {}", new Object[]{principal});

        loginContext = null;
    } catch (LoginException e) {
        throw new LoginException("Logout failed due to: " + e.getMessage());
    }
}
 
Example 6
Source File: KerberosUsernamePasswordAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if user with given username exists in kerberos database
 *
 * @param username username without Kerberos realm attached or with correct realm attached
 * @return true if user available
 */
public boolean isUserAvailable(String username) {
    logger.debugf("Checking existence of user: %s", username);
    try {
        String principal = getKerberosPrincipal(username);
        loginContext = new LoginContext("does-not-matter", null,
                createJaasCallbackHandler(principal, "fake-password-which-nobody-has"),
                createJaasConfiguration());

        loginContext.login();

        throw new IllegalStateException("Didn't expect to end here");
    } catch (LoginException le) {
        String message = le.getMessage();
        logger.debugf("Message from kerberos: %s", message);

        checkKerberosServerAvailable(le);

        // Bit cumbersome, but seems to work with tested kerberos servers
        boolean exists = (!message.contains("Client not found"));
        return exists;
    }
}
 
Example 7
Source File: SpnegoAuthenticator.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
private Subject principalLogin(String principal, File keytabFile) {
    try {
        LoginContext loginContext = new LoginContext(
                "", new Subject(), null, getConfiguration(principal, keytabFile));
        loginContext.login();
        return loginContext.getSubject();
    } catch (LoginException e) {
        throw new RuntimeException("Failed login for principal `" + principal + "` with keytab `" + keytabFile.getPath() + "`. Error message: " + e.getMessage());
    }
}
 
Example 8
Source File: HTTPKerberosAuthInterceptor.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public HTTPKerberosAuthInterceptor(String host, Map<String,String> krbOptions) {
  this.host = host;
  this.krbOptions = krbOptions;
  try {
    buildSubjectCredentials();
  } catch (LoginException e) {
    throw new FailedRequestException(e.getMessage(), e);
  }
}
 
Example 9
Source File: HttpBackend.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
private JsonResponse doPrivilegedRequest(String method, String url, ArrayList<Header> headers, StringEntity entity)
        throws CygnusRuntimeError {
    try {
        LoginContext loginContext = new LoginContext("cygnus_krb5_login",
                new KerberosCallbackHandler(krb5User, krb5Password));
        loginContext.login();
        PrivilegedRequest req = new PrivilegedRequest(method, url, headers, entity);
        return createJsonResponse((HttpResponse) Subject.doAs(loginContext.getSubject(), req));
    } catch (LoginException e) {
        throw new CygnusRuntimeError("Privileged request error", "LoginException", e.getMessage());
    } // try catch
}
 
Example 10
Source File: AbstractKerberosUser.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a login using the specified principal and keytab.
 *
 * @throws LoginException if the login fails
 */
@Override
public synchronized void login() throws LoginException {
    if (isLoggedIn()) {
        return;
    }

    try {
        // If it's the first time ever calling login then we need to initialize a new context
        if (loginContext == null) {
            LOGGER.debug("Initializing new login context...");
            if (this.subject == null) {
                // only create a new subject if a current one does not exist
                // other classes may be referencing an existing subject and replacing it may break functionality of those other classes after relogin
                this.subject = new Subject();
            }
            this.loginContext = createLoginContext(subject);
        }

        loginContext.login();
        loggedIn.set(true);
        LOGGER.debug("Successful login for {}", new Object[]{principal});
    } catch (LoginException le) {
        LoginException loginException = new LoginException("Unable to login with " + principal + " due to: " + le.getMessage());
        loginException.setStackTrace(le.getStackTrace());
        throw loginException;
    }
}
 
Example 11
Source File: JaasAuthenticationProvider.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Authentication authenticate(final Credentials credentials) throws AuthenticationException {
    if (realmName == null) { // configuration is not yet ready or set
        realmName = DEFAULT_REALM;
    }

    if (!(credentials instanceof UsernamePasswordCredentials)) {
        throw new AuthenticationException("Unsupported credentials passed to provider.");
    }

    UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) credentials;
    final String name = userCredentials.getUsername();
    final char[] password = userCredentials.getPassword().toCharArray();

    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Principal userPrincipal = new GenericUser(name);
        Subject subject = new Subject(true, Set.of(userPrincipal), Collections.emptySet(), Set.of(userCredentials));

        Thread.currentThread().setContextClassLoader(ManagedUserLoginModule.class.getClassLoader());
        LoginContext loginContext = new LoginContext(realmName, subject, new CallbackHandler() {
            @Override
            public void handle(@NonNullByDefault({}) Callback[] callbacks)
                    throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof PasswordCallback) {
                        ((PasswordCallback) callback).setPassword(password);
                    } else if (callback instanceof NameCallback) {
                        ((NameCallback) callback).setName(name);
                    } else {
                        throw new UnsupportedCallbackException(callback);
                    }
                }
            }
        }, new ManagedUserLoginConfiguration());
        loginContext.login();

        return getAuthentication(name, loginContext.getSubject());
    } catch (LoginException e) {
        throw new AuthenticationException(e.getMessage());
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
 
Example 12
Source File: JAASLoginInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(final Message message) {
    if (allowNamedPrincipals) {
        SecurityContext sc = message.get(SecurityContext.class);
        if (sc != null && sc.getUserPrincipal() != null
            && sc.getUserPrincipal().getName() != null) {
            return;
        }
    }

    CallbackHandler handler = getFirstCallbackHandler(message);

    if (handler == null && !allowAnonymous) {
        throw new AuthenticationException("Authentication required but no authentication information was supplied");
    }

    try {
        LoginContext ctx = new LoginContext(getContextName(), null, handler, loginConfig);
        ctx.login();
        Subject subject = ctx.getSubject();
        String name = getUsername(handler);
        message.put(SecurityContext.class, createSecurityContext(name, subject));

        // Run the further chain in the context of this subject.
        // This allows other code to retrieve the subject using pure JAAS
        if (useDoAs) {
            Subject.doAs(subject, new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    InterceptorChain chain = message.getInterceptorChain();
                    if (chain != null) {
                        message.put("suspend.chain.on.current.interceptor", Boolean.TRUE);
                        chain.doIntercept(message);
                    }
                    return null;
                }
            });
        }

    } catch (LoginException ex) {
        String errorMessage = "Authentication failed: " + ex.getMessage();
        LOG.log(Level.FINE, errorMessage, ex);
        if (reportFault) {
            AuthenticationException aex = new AuthenticationException(errorMessage);
            aex.initCause(ex);
            throw aex;

        }
        throw new AuthenticationException("Authentication failed (details can be found in server log)");
    }
}