List of usage examples for javax.security.auth.login LoginContext login
public void login() throws LoginException
From source file:org.qualipso.funkyfactory.test.clock.functionnal.ClockServiceFunctionalTest.java
/** * Test the getTime ClockService authentified *///w ww . j a va 2 s. c o m @Test public void testGetTimeAuthentified() { logger.debug("Testing ClockService authentified"); try { UsernamePasswordHandler uph = new UsernamePasswordHandler("kermit", "thefrog"); LoginContext loginContext = new LoginContext("tests", uph); loginContext.login(); messageTest(); loginContext.logout(); } catch (LoginException e) { logger.error("Problem when loggin in"); logger.error(e.getMessage(), e); fail(e.getMessage()); } catch (NamingException e) { logger.error("Problem when doing the service lookup"); logger.error(e.getMessage(), e); fail(e.getMessage()); } catch (ClockServiceException e) { logger.error("Problem when calling the service"); logger.error(e.getMessage(), e); fail(e.getMessage()); } }
From source file:org.qualipso.funkyfactory.ui.login.server.LoginServletImpl.java
public Boolean login(String username, String password) { logger.info("login: USERNAME=" + username + " --- PASSWORD=" + password); UsernamePasswordHandler uph = new UsernamePasswordHandler(username, password); LoginContext loginContext; try {/* ww w.jav a 2 s.c o m*/ loginContext = new LoginContext("client-login", uph); loginContext.login(); } catch (LoginException e) { logger.info("ca pete dans le login"); e.printStackTrace(); } try { logger.info("Profile Path" + membership.getProfilePathForConnectedIdentifier()); } catch (MembershipServiceException e) { logger.info("ca pete dans le membership"); e.printStackTrace(); } catch (EJBAccessException e1) { logger.info("Thou Shalt Not Pass !!!"); return new Boolean(false); } HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); session.setAttribute("username", username); session.setAttribute("password", password); logger.info("session stored: " + username + " " + password); String sessionid = session.getId(); logger.info("login session: " + sessionid); Cookie ssocookie = new Cookie("SSOSESSIONID", sessionid); ssocookie.setPath("/"); this.getThreadLocalResponse().addCookie(ssocookie); storeDataInContext(sessionid, username, password); return true; }
From source file:org.rhq.enterprise.server.auth.SubjectManagerBean.java
private void _checkAuthentication(String username, String password) throws LoginException { try {//from w w w.j a va2 s . c o m UsernamePasswordHandler handler = new UsernamePasswordHandler(username, password.toCharArray()); LoginContext loginContext; loginContext = new LoginContext(CustomJaasDeploymentServiceMBean.SECURITY_DOMAIN_NAME, handler); loginContext.login(); loginContext.getSubject().getPrincipals().iterator().next(); loginContext.logout(); } catch (javax.security.auth.login.LoginException e) { throw new LoginException(e.getMessage()); } }
From source file:org.sakaiproject.component.kerberos.user.JassAuthenticate.java
public boolean attemptAuthentication(String username, String password) { LoginContext userLoginContext = null; LoginContext serverLoginContext = null; try {//from w w w . ja va 2s . c o m // This may well fail so run catch exceptions here. try { userLoginContext = new LoginContext(userPrincipal, new UsernamePasswordCallback(username, password)); userLoginContext.login(); } catch (LoginException le) { if (log.isDebugEnabled()) { log.debug("Failed to authenticate " + username, le); } return false; } if (!verifyServiceTicket) { log.debug("Authenticated ok and not attempting service ticket verification"); return true; } // Shouldn't ever fail serverLoginContext = new LoginContext(servicePrincipal, new NullCallbackHandler()); serverLoginContext.login(); GSSManager manager = GSSManager.getInstance(); Oid kerberos = new Oid("1.2.840.113554.1.2.2"); GSSName serverName = manager.createName(serverGSS, GSSName.NT_HOSTBASED_SERVICE); clientContext = manager.createContext(serverName, kerberos, null, GSSContext.DEFAULT_LIFETIME); serverContext = manager.createContext((GSSCredential) null); int exchanges = 0; while (!clientContext.isEstablished() && !serverContext.isEstablished() && !(initTokens == null && acceptTokens == null)) { Subject.doAs(userLoginContext.getSubject(), new InitiatorAction()); Subject.doAs(serverLoginContext.getSubject(), new AcceptorAction()); if (++exchanges > exchangeLimit) { throw new RuntimeException("Too many tickets exchanged (" + exchangeLimit + ")."); } } log.debug("Authenticated ok and verified service ticket"); return true; } catch (GSSException gsse) { log.warn("Failed to verify ticket.", gsse); } catch (LoginException le) { log.warn("Failed to login with keytab.", le); } finally { try { if (clientContext != null) clientContext.dispose(); if (serverContext != null) serverContext.dispose(); if (userLoginContext != null) userLoginContext.logout(); if (serverLoginContext != null) serverLoginContext.logout(); } catch (Exception e) { log.error("Failed to tidy up after attempting authentication.", e); } } return false; }
From source file:org.sakaiproject.component.kerberos.user.KerberosUserDirectoryProvider.java
/** * Check if the user id is known to kerberos. * /*w w w .j a v a 2 s .c o m*/ * @param user * The user id. * @return true if successful, false if not. */ private boolean userKnownToKerberos(String user) { // use a dummy password String pw = "dummy"; // Obtain a LoginContext, needed for authentication. // Tell it to use the LoginModule implementation specified // in the JAAS login configuration file and to use // use the specified CallbackHandler. LoginContext lc = null; try { CallbackHandler t = new UsernamePasswordCallback(user, pw); lc = new LoginContext(m_logincontext, t); } catch (LoginException le) { if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + le.toString()); return false; } catch (SecurityException se) { if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + se.toString()); return false; } try { // attempt authentication lc.login(); lc.logout(); if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(" + user + "): Kerberos auth success"); return true; } catch (LoginException le) { String msg = le.getMessage(); // if this is the message, the user was good, the password was bad if (msg.startsWith(m_knownusermsg)) { if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user known (bad pw)"); return true; } // the other message is when the user is bad: if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user unknown or invalid"); return false; } }
From source file:org.sonar.plugins.ldap.LdapAuthenticator.java
private boolean checkPasswordUsingGssapi(String principal, String password, String ldapKey) { // Use our custom configuration to avoid reliance on external config Configuration.setConfiguration(new Krb5LoginConfiguration()); LoginContext lc; try {/* ww w . ja v a 2 s . co m*/ lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password)); lc.login(); } catch (LoginException e) { // Bad username: Client not found in Kerberos database // Bad password: Integrity check on decrypted field failed LOG.debug("Password not valid for {} in server {}: {}", principal, ldapKey, e.getMessage()); return false; } try { lc.logout(); } catch (LoginException e) { LOG.warn("Logout fails", e); } return true; }
From source file:org.sonar.plugins.ldap.LdapContextFactory.java
private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials) throws NamingException { Configuration.setConfiguration(new Krb5LoginConfiguration()); InitialDirContext initialDirContext; try {/*from w w w . java 2s . co m*/ LoginContext lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, credentials)); lc.login(); initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() { @Override public InitialDirContext run() throws NamingException { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, DEFAULT_REFERRAL); return new InitialLdapContext(env, null); } }); } catch (LoginException | PrivilegedActionException e) { NamingException namingException = new NamingException(e.getMessage()); namingException.initCause(e); throw namingException; } return initialDirContext; }
From source file:org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.java
/** * Attempts to login the user given the Authentication objects principal and * credential//from w ww .j ava 2s . c o m * * @param auth The Authentication object to be authenticated. * * @return The authenticated Authentication object, with it's grantedAuthorities set. * * @throws AuthenticationException This implementation does not handle 'locked' or * 'disabled' accounts. This method only throws a AuthenticationServiceException, with * the message of the LoginException that will be thrown, should the * loginContext.login() method fail. */ public Authentication authenticate(Authentication auth) throws AuthenticationException { if (!(auth instanceof UsernamePasswordAuthenticationToken)) { return null; } UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth; Set<GrantedAuthority> authorities; try { // Create the LoginContext object, and pass our InternallCallbackHandler LoginContext loginContext = createLoginContext(new InternalCallbackHandler(auth)); // Attempt to login the user, the LoginContext will call our // InternalCallbackHandler at this point. loginContext.login(); // Create a set to hold the authorities, and add any that have already been // applied. authorities = new HashSet<>(); // Get the subject principals and pass them to each of the AuthorityGranters Set<Principal> principals = loginContext.getSubject().getPrincipals(); for (Principal principal : principals) { for (AuthorityGranter granter : this.authorityGranters) { Set<String> roles = granter.grant(principal); // If the granter doesn't wish to grant any authorities, it should // return null. if ((roles != null) && !roles.isEmpty()) { for (String role : roles) { authorities.add(new JaasGrantedAuthority(role, principal)); } } } } // Convert the authorities set back to an array and apply it to the token. JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), request.getCredentials(), new ArrayList<>(authorities), loginContext); // Publish the success event publishSuccessEvent(result); // we're done, return the token. return result; } catch (LoginException loginException) { AuthenticationException ase = this.loginExceptionResolver.resolveException(loginException); publishFailureEvent(request, ase); throw ase; } }
From source file:org.springframework.security.extensions.kerberos.sun.SunJaasKerberosClient.java
@Override public String login(String username, String password) { LOG.debug("Trying to authenticate " + username + " with Kerberos"); String validatedUsername;// www . j a v a2 s . c o m try { 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) { throw new BadCredentialsException("Kerberos authentication failed", e); } return validatedUsername; }
From source file:org.springframework.security.extensions.kerberos.SunJaasKerberosClient.java
public String login(String username, String password) { LOG.debug("Trying to authenticate " + username + " with Kerberos"); String validatedUsername;//from w w w.j ava 2 s . com try { 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) { throw new BadCredentialsException("Kerberos authentication failed", e); } return validatedUsername; }