Example usage for javax.security.auth.login LoginException printStackTrace

List of usage examples for javax.security.auth.login LoginException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:AuthenticateNT.java

public static void main(String[] args) {
    try {/*w  w  w  . j  a v a2 s  .c o  m*/
        LoginContext loginContext = new LoginContext("AuthenticateNT");
        loginContext.login();
        System.out.println("Login Successful");
        Subject subject = loginContext.getSubject();
        System.out.println(subject);
        Subject.doAs(subject, new WriteFileAction());
        loginContext.logout();
        System.exit(0);
    } catch (LoginException loginException) {
        loginException.printStackTrace();
        System.exit(-1);
    }
}

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 {/* w w w .  j a va  2  s .c o  m*/
        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:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java

@Override
public void afterResponse(HandshakeResponse hr) {
    try {//from   www .  j ava  2  s. c o m
        if (loginContext != null) {
            loginContext.logout();
        }
    } catch (LoginException e) {
        e.printStackTrace();
        //work is done just ignore
    }
}

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

public void login() {
    try {//  www .j a v  a 2s . 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:com.redhat.topicindex.security.FedoraAccountSystem.java

@SuppressWarnings("unchecked")
private boolean authenticate() throws LoginException {
    if (password == null || username == null)
        throw new LoginException("No Username/Password found");
    if (password.equals("") || username.equals(""))
        throw new LoginException("No Username/Password found");

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(FEDORA_JSON_URL);

    try {/* www . j a  v  a2s.c om*/
        // Generate the data to send
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new NameValuePair("username", username));
        formparams.add(new NameValuePair("user_name", username));
        formparams.add(new NameValuePair("password", String.valueOf(password)));
        formparams.add(new NameValuePair("login", "Login"));

        method.addParameters(formparams.toArray(new NameValuePair[formparams.size()]));

        // Send the data and get the response
        client.executeMethod(method);

        // Handle the response
        BufferedReader br = new BufferedReader(
                new InputStreamReader(new ByteArrayInputStream(method.getResponseBody())));

        JSONParser parser = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            public List creatArrayContainer() {
                return new LinkedList();
            }

            public Map createObjectContainer() {
                return new LinkedHashMap();
            }
        };

        // Parse the response to check authentication success and valid groups
        String line;
        while ((line = br.readLine()) != null) {
            Map json = (Map) parser.parse(line, containerFactory);
            if (json.containsKey("success") && json.containsKey("person")) {
                if (json.get("person") instanceof LinkedHashMap) {
                    LinkedHashMap person = (LinkedHashMap) json.get("person");
                    if (person.get("status").equals("active")) {
                        if (person.containsKey("approved_memberships")) {
                            if (person.get("approved_memberships") instanceof LinkedList) {
                                if (!checkCLAAgreement(((LinkedList) person.get("approved_memberships")))) {
                                    throw new LoginException("FAS authentication failed for " + username
                                            + ". Contributor License Agreement not yet signed");
                                }
                            } else if (person.get("approved_memberships") instanceof LinkedHashMap) {
                                if (!checkCLAAgreement(((LinkedHashMap) person.get("approved_memberships")))) {
                                    throw new LoginException("FAS authentication failed for " + username
                                            + ". Contributor License Agreement not yet signed");
                                }
                            }
                        } else {
                            throw new LoginException("FAS authentication failed for " + username
                                    + ". Contributor License Agreement not yet signed");
                        }
                    } else {
                        throw new LoginException(
                                "FAS authentication failed for " + username + ". Account is not active");
                    }
                }
            } else {
                throw new LoginException("Error: FAS authentication failed for " + username);
            }
        }
    } catch (LoginException e) {
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    return true;
}

From source file:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

/**
 * Init GSSContext for negotiation.//from w  w  w . ja v a  2 s .co m
 *
 * @param server servername only (e.g: radar.it.su.se)
 */
protected void init(String server, UsernamePasswordCredentials credentials) throws GSSException {
    LOG.info("init " + server);

    // Create a callback handler
    Configuration.setConfiguration(null);
    CallbackHandler callbackHandler = new CustomNegotiateCallbackHandler(credentials.getUserName(),
            credentials.getPassword());
    PrivilegedExceptionAction action = new MyAction(server);
    LoginContext con = null;

    try {
        CustomConfiguration cc = getCustomConfiguration(credentials);

        // Create a LoginContext with a callback handler
        con = new LoginContext("com.sun.security.jgss.login", null, callbackHandler, cc);

        Configuration.setConfiguration(cc);
        // Perform authentication
        con.login();
    } catch (LoginException e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    } catch (Exception e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    }

    // Perform action as authenticated user
    Subject subject = con.getSubject();
    //LOG.trace("Subject is :"+ subject.toString());

    LOG.info("Authenticated principal:**** " + subject.getPrincipals());

    try {
        Subject.doAs(subject, action);
    } catch (PrivilegedActionException e) {
        e.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:ispyb.server.security.DatabaseLoginModuleSecurityFilter.java

/**
 * Authenticate a user./*  w  w w .java  2s  .  c  o m*/
 * 
 * @param username a proposal id
 * @param password a password, either sent from the Web User Office Tool or as entered by the user from ISPyB portal
 *
 * @return null if the user cannot be authenticated, otherwise a Principal object is returned
 */
public boolean booleanAuthenticate(String username, String password) {

    boolean valid = false;

    // retrieve, decode & decrypt password received
    if (Constants.SITE_IS_SOLEIL()) {
        password = getDecryptPass(password);
    }

    debug_ = "true".equalsIgnoreCase((String) getDebug());

    try {
        // verify user credential  
        DatabaseLoginModuleHelper.verifyCredentials(getSecurityOptions(), username, password);
        valid = true;

        // get user's role to log in to 
        if (usernameRoles == null) {
            usernameRoles = DatabaseLoginModuleHelper.getRoleNamesForUser(getSecurityOptions(), username,
                    password);
        }

        String value = null;
        for (String role_ : usernameRoles) {
            value = role_;
            if (debug_) {
                LOG.debug(".booleanAuthenticate() --- usernameRoles value = " + value);
            }
        }

    } catch (LoginException e) {
        LOG.error(".booleanAuthenticate() --- Exception -- wrong crendentials " + " validAuthentication = "
                + valid);
        e.printStackTrace();
        return valid;
    }
    return true;
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * It does the Kerberos authentication when it has to be done through 
 * username and password. It looks in the default Kerberos domain defined 
 * in the Kerberos config file (krb5.ini or krb5.conf) if there is a valid 
 * user with those credentials. If so, it gets his/her Kerberos ticket.
 * //ww  w  .  jav a 2  s.  c o  m
 * @param userCred username and password credentials
 *
 * @return the method result in HTTP error format
 */
public int authUsernamePassword(Credential userCred) {

    int result = HttpServletResponse.SC_UNAUTHORIZED;

    Krb5LoginModule login = null;
    userSubject = new Subject();

    logger.debug("authUsernamePassword: using username and password");

    try {

        //Create config objects and pass the credentials      
        Map state = new HashMap();
        UsernamePasswordCredentials usrpwdCred = new UsernamePasswordCredentials(userCred.getUsername(),
                userCred.getPassword());
        state.put("javax.security.auth.login.name", usrpwdCred.getUserName());
        state.put("javax.security.auth.login.password", usrpwdCred.getPassword().toCharArray());
        state.put("java.security.krb5.conf", krbini);

        if (logger.isDebugEnabled()) {
            logger.debug("Username: " + usrpwdCred.getUserName());
        }

        Map option = new HashMap();
        String isDebug = "false";
        if (logger.isDebugEnabled()) {
            isDebug = "true";
        }
        option.put("debug", isDebug);
        option.put("tryFirstPass", "true");
        option.put("useTicketCache", "false");
        option.put("doNotPrompt", "false");
        option.put("storePass", "false");
        option.put("forwardable", "true");

        login = new Krb5LoginModule();
        login.initialize(userSubject, new NegotiateCallbackHandler(), state, option);

        if (login.login()) {
            login.commit();
            logger.debug("Login commit");
            if (id == null) {
                username = usrpwdCred.getUserName();
                id = username;
            }
            logger.debug("username is ... " + id);
            result = HttpServletResponse.SC_OK;
        }
    } catch (LoginException e) {
        logger.error("LoginException while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_UNAUTHORIZED;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return result;

}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosSSOFilter.java

/**
 * Filters every request made to the server to determine and set authentication of the user.
 * 1. Find out if the user is already authenticated (by checking the securityContext).
 * 2. Otherwise, authenticate the user from his Kerberos ticket and,
 * 3. Set him as authenticated by setting a new securityContext.
 * During the negotiation process used by Spnego, none of the filters after this one in the chain
 * will be allowed to execute./*ww  w  . j a va 2s. c  om*/
 *
 * @param request the Servlet request to serve
 * @param response the Servlet response to serve
 * @param chain the filter chain determining which filter will execute after ours.
 * @throws IOException if redirection goes wrong or if another filter in the chain fails.
 * @throws ServletException if the authentication fails.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            || containsBypassHeader(request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String userContentPath = httpRequest.getContextPath() + "/userContent";

    if (httpRequest.getRequestURI().startsWith(userContentPath)) {
        chain.doFilter(request, response);
        return;
    }

    SpnegoHttpServletResponse spnegoHttpResponse = new SpnegoHttpServletResponse(
            (HttpServletResponse) response);

    if (PluginImpl.getInstance().isRedirectEnabled()
            && !httpRequest.getLocalAddr().equals(httpRequest.getRemoteAddr())) {
        // If Local and Remote address is the same, the user is Localhost and shouldn't be redirected.

        String requestedDomain = new URL(httpRequest.getRequestURL().toString()).getHost();
        String requestedURL = httpRequest.getRequestURL().toString();
        if (!requestedDomain.toLowerCase().contains(PluginImpl.getInstance().getRedirect().toLowerCase())) {

            String redirect = requestedURL.replaceFirst(requestedDomain,
                    requestedDomain + "." + PluginImpl.getInstance().getRedirect());
            spnegoHttpResponse.sendRedirect(redirect);
        }
    }

    // A user is "always" authenticated by Jenkins as anonymous when not authenticated in any other way.
    if (SecurityContextHolder.getContext().getAuthentication() == null
            || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
            || Functions.isAnonymous()) {
        Functions.advertiseHeaders((HttpServletResponse) response); //Adds headers for CLI

        Principal principal;

        try {
            principal = authenticator.authenticate(httpRequest, spnegoHttpResponse);
        } catch (LoginException e) {
            logger.log(Level.WARNING, "Failed to fetch spnegoPrincipal name for user");
            chain.doFilter(request, spnegoHttpResponse);
            return;
        }

        // Expecting negotiation
        if (principal == null) {
            return;
        }

        String principalName = principal.getName();

        if (principalName.contains("@")) {
            principalName = principalName.substring(0, principalName.indexOf("@"));
        }

        try {
            SecurityRealm realm = Jenkins.getInstance().getSecurityRealm();
            UserDetails userDetails = realm.loadUserByUsername(principalName);
            Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                    userDetails.getPassword(), userDetails.getAuthorities());

            ACL.impersonate(authToken);
            if (Jenkins.getVersion().isNewerThan(new VersionNumber("1.568"))) {
                try {
                    Method fireLoggedIn = SecurityListener.class.getMethod("fireLoggedIn", String.class);
                    fireLoggedIn.invoke(null, userDetails.getUsername());
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to invoke fireLoggedIn method", e);
                }
            }
            logger.log(Level.FINE, "Authenticated user {0}", userDetails.getUsername());
        } catch (UsernameNotFoundException e) {
            logger.log(Level.WARNING, "Username {0} not registered by Jenkins", principalName);
        } catch (NullPointerException e) {
            logger.log(Level.WARNING, "User authentication failed");
            e.printStackTrace();
        } catch (DataAccessException e) {
            logger.log(Level.WARNING, "No access to user database");
            e.printStackTrace();
        }
    }

    chain.doFilter(request, response);
}