Java Code Examples for javax.security.auth.login.LoginException

The following are top voted examples for showing how to use javax.security.auth.login.LoginException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: boutique-de-jus   File: LoginModuleAuthSupport.java   Source Code and License 7 votes vote down vote up
@Override
public Optional<Subject> map(final Optional<Object> wrapper) {
    try {
        LOG.info("logging in user as {}", username);
        LoginContext lc = new LoginContext("PropertyFile", callbacks -> {
            LOG.info("Callback Handler invoked ");
            Stream.of(callbacks).forEach(cb -> {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName(username);
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword(password.toCharArray());
                }
            });
        });
        lc.login();
        return Optional.of(lc.getSubject());
    } catch (LoginException e) {
        LOG.error("Authentication failed", e);
        return Optional.empty();
    }
}
 
Example 2
Project: calcite-avatica   File: KerberosConnection.java   Source Code and License 7 votes vote down vote up
/**
 * Performs a kerberos login, possibly logging out first.
 *
 * @param prevContext The LoginContext from the previous login, or null
 * @param conf JAAS Configuration object
 * @param subject The JAAS Subject
 * @return The context and subject from the login
 * @throws LoginException If the login failed.
 */
Entry<LoginContext, Subject> login(LoginContext prevContext, Configuration conf,
    Subject subject) throws LoginException {
  // Is synchronized by the caller

  // If a context was provided, perform a logout first
  if (null != prevContext) {
    prevContext.logout();
  }

  // Create a LoginContext given the Configuration and Subject
  LoginContext loginContext = createLoginContext(conf);
  // Invoke the login
  loginContext.login();
  // Get the Subject from the context and verify it's non-null (null would imply failure)
  Subject loggedInSubject = loginContext.getSubject();
  if (null == loggedInSubject) {
    throw new RuntimeException("Failed to perform Kerberos login");
  }

  // Send it back to the caller to use with launchRenewalThread
  return new AbstractMap.SimpleEntry<>(loginContext, loggedInSubject);
}
 
Example 3
Project: ZooKeeper   File: SaslQuorumAuthLearner.java   Source Code and License 6 votes vote down vote up
public SaslQuorumAuthLearner(boolean quorumRequireSasl,
        String quorumServicePrincipal, String loginContext)
                throws SaslException {
    this.quorumRequireSasl = quorumRequireSasl;
    this.quorumServicePrincipal = quorumServicePrincipal;
    try {
        AppConfigurationEntry entries[] = Configuration
            .getConfiguration()
            .getAppConfigurationEntry(loginContext);
        if (entries == null || entries.length == 0) {
            throw new LoginException("SASL-authentication failed because"
                                     + " the specified JAAS configuration "
                                     + "section '" + loginContext
                                     + "' could not be found.");
        }
        this.learnerLogin = new Login(loginContext,
                                new SaslClientCallbackHandler(null, "QuorumLearner"));
        this.learnerLogin.startThreadIfNeeded();
    } catch (LoginException e) {
        throw new SaslException("Failed to initialize authentication mechanism using SASL", e);
    }
}
 
Example 4
Project: jdk8u-jdk   File: SmartLoginModule.java   Source Code and License 6 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    if (!succeeded) {
        return false;
    } else {
        // add a Principal (authenticated identity) to the Subject
        // assume the user we authenticated is the SamplePrincipal
        userPrincipal = new SamplePrincipal(username);
        if (!subject.getPrincipals().contains(userPrincipal)) {
            subject.getPrincipals().add(userPrincipal);
        }
        // in any case, clean out state
        username = null;
        password = null;
        commitSucceeded = true;
        return true;
    }
}
 
Example 5
Project: OpenJSharp   File: Krb5Util.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the ticket corresponding to the client/server principal
 * pair from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getTicket(GSSCaller caller,
    String clientPrincipal, String serverPrincipal,
    AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
        SubjectComber.find(accSubj, serverPrincipal, clientPrincipal,
              KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
            serverPrincipal, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example 6
Project: oscm   File: ConfirmationBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void initialize_SSOAutoLogin_Exception() throws Exception {
    // given
    voUser.setStatus(UserAccountStatus.LOCKED_NOT_CONFIRMED);
    String encodedString = ParameterEncoder.encodeParameters(new String[] {
            userId, orgId, "MPID", String.valueOf(serviceKey) });
    confirmationBean.setEncodedParam(encodedString);
    doReturn(Boolean.TRUE).when(confirmationBean).isServiceProvider();
    doThrow(new LoginException("")).when(confirmationBean).loginUser(
            eq(voUser), anyString(), eq(request), eq(session));

    // when
    confirmationBean.initialize();

    // then
    assertEquals(serviceKey, sessionBean.getSubscribeToServiceKey());
    verify(confirmationBean, times(1)).addMessage(anyString(),
            eq(FacesMessage.SEVERITY_ERROR),
            eq(BaseBean.ERROR_USER_CONFIRMED_LOGIN_FAIL));
}
 
Example 7
Project: cas-5.1.0   File: MockLoginModule.java   Source Code and License 6 votes vote down vote up
@Override
public boolean login() throws LoginException {
    final Callback[] callbacks = new Callback[] {new NameCallback("f"), new PasswordCallback("f", false)};
    try {
        this.callbackHandler.handle(callbacks);
    } catch (final Exception e) {
        throw new LoginException();
    }

    final String userName = ((NameCallback) callbacks[0]).getName();
    final String password = new String(((PasswordCallback) callbacks[1]).getPassword());

    if ("test".equals(userName) && "test".equals(password)) {
        return true;
    }

    throw new LoginException();
}
 
Example 8
Project: openjdk-jdk10   File: DynamicConfigurationTest.java   Source Code and License 6 votes vote down vote up
public static void testLogin(String confName, char[] passwd,
        Configuration cf, boolean expectException) {
    try {
        CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
        LoginContext lc = new LoginContext(confName, new Subject(),
                ch, cf);
        lc.login();
        if (expectException) {
            throw new RuntimeException("Login Test failed: "
                    + "expected LoginException not thrown");
        }
    } catch (LoginException le) {
        if (!expectException) {
            System.out.println("Login Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 9
Project: oscm   File: AuthorizationFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void loginUser_UserLocked_BluePortal() throws Exception {
    // given
    VOUser voUser = createVoUser("userId", UserAccountStatus.LOCKED);
    doReturn(voUser).when(identityServiceMock).getUser(any(VOUser.class));

    createSessionMock(serviceAccessMock, "/oscm-portal/", false);

    doReturn("").when(authReqDataMock).getMarketplaceId();
    doThrow(new LoginException()).when(serviceAccessMock).login(
            any(VOUser.class), anyString(), any(HttpServletRequest.class),
            any(HttpServletResponse.class));

    // when
    boolean result = authFilter
            .loginUser(chainMock, requestMock, responseMock, userDetails,
                    authReqDataMock, identityServiceMock);

    // then
    assertFalse("Forward must be performed", result);
    verify(requestMock, times(1)).setAttribute(
            Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_USER_LOCKED);
    verify(authFilter, times(1)).forward(BaseBean.ERROR_PAGE, requestMock,
            responseMock);
}
 
Example 10
Project: oscm   File: UserBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void login_UserLocked_SAMLSP() throws Exception {
    VOUser voUser = createVoUser("userId", UserAccountStatus.LOCKED);
    doReturn("userId").when(requestMock).getParameter(
            eq(UserBean.SAMPSP_FORM + Constants.REQ_PARAM_USER_ID));
    doReturn(Boolean.TRUE).when(userBean).isServiceProvider();
    doReturn(voUser).when(idServiceMock).getUser(any(VOUser.class));
    doThrow(new LoginException()).when(serviceAccessMock).login(eq(voUser),
            anyString(), any(HttpServletRequest.class),
            any(HttpServletResponse.class));
    doReturn(BaseBean.SAML_SP_LOGIN_AUTOSUBMIT_PAGE).when(requestMock)
            .getServletPath();
    // when
    String result = userBean.login();
    // then
    verify(requestMock, times(1)).setAttribute(
            eq(Constants.REQ_ATTR_ERROR_KEY),
            eq(BaseBean.ERROR_USER_LOCKED));
    assertEquals(BaseBean.OUTCOME_MARKETPLACE_ERROR_PAGE, result);
}
 
Example 11
Project: servlet-auth   File: MyLoginServlet.java   Source Code and License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final String username = request.getParameter("username");
    final String password = request.getParameter("password");

    HttpSession session = request.getSession(false);
    if (session != null) {
        session.removeAttribute("user");
    }

    // Do your crazy complex login procedure here
    if (username.equalsIgnoreCase("test") && password.equalsIgnoreCase("test")) {
        request.getSession().setAttribute("user", new MyCustomPrincipal(username, Arrays.asList("manager", "admin")));
        System.out.println("Principal is: " + request.getSession(false).getAttribute("user"));
    } else {
        // what should happen when login fails
        try {
            throw new LoginException("You're not test=test user !");
        } catch (LoginException e) {
            e.printStackTrace();
        }
    }

    response.sendRedirect(request.getContextPath() + "/");
}
 
Example 12
Project: jdk8u-jdk   File: DynamicConfigurationTest.java   Source Code and License 6 votes vote down vote up
public static void testLogin(String confName, char[] passwd,
        Configuration cf, boolean expectException) {
    try {
        CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
        LoginContext lc = new LoginContext(confName, new Subject(),
                ch, cf);
        lc.login();
        if (expectException) {
            throw new RuntimeException("Login Test failed: "
                    + "expected LoginException not thrown");
        }
    } catch (LoginException le) {
        if (!expectException) {
            System.out.println("Login Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 13
Project: openjdk-jdk10   File: LCTest.java   Source Code and License 6 votes vote down vote up
@Override
public boolean login() throws LoginException {
    LCTest.logAction("login");
    if (callbackHandler == null) {
        throw new LoginException("No CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        password = new String(((PasswordCallback) callbacks[1])
                .getPassword());
        if (username.equals(LCTest.USER_NAME) &&
                password.equals(LCTest.PASSWORD)) {
            succeeded = true;
            return true;
        }
        throw new FailedLoginException("Incorrect username/password!");
    } catch (IOException | UnsupportedCallbackException e) {
        throw new LoginException("Login failed: " + e.getMessage());
    }
}
 
Example 14
Project: OpenJSharp   File: KeyStoreLoginModule.java   Source Code and License 6 votes vote down vote up
/**
 * Logout a user.
 *
 * <p> This method removes the Principals, public credentials and the
 * private credentials that were added by the <code>commit</code> method.
 *
 * <p> If the loaded KeyStore's provider extends
 * <code>java.security.AuthProvider</code>,
 * then the provider's <code>logout</code> method is invoked.
 *
 * <p>
 *
 * @exception LoginException if the logout fails.
 *
 * @return true in all cases since this <code>LoginModule</code>
 *          should not be ignored.
 */

public boolean logout() throws LoginException {
    if (debug)
        debugPrint("Entering logout " + status);
    switch (status) {
    case UNINITIALIZED:
        throw new LoginException
            ("The login module is not initialized");
    case INITIALIZED:
    case AUTHENTICATED:
    default:
       // impossible for LoginModule to be in AUTHENTICATED
       // state
       // assert status != AUTHENTICATED;
        return false;
    case LOGGED_IN:
        logoutInternal();
        return true;
    }
}
 
Example 15
Project: openjdk-jdk10   File: DynamicConfigurationTest.java   Source Code and License 6 votes vote down vote up
public static void testConfigName(String confName,
        boolean expectException) {
    String expectedMsg = "No LoginModules configured for " + confName;
    try {
        LoginContext lc = new LoginContext(confName, new Subject(),
                new MyCallbackHandler(), new MyConfiguration());

        if (expectException) {
            throw new RuntimeException("Wrong Config Name Test failed: "
                    + "expected LoginException not thrown.");
        }
    } catch (LoginException le) {
        if (!expectException || !le.getMessage().equals(expectedMsg)) {
            System.out.println("Wrong Config Name Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 16
Project: discord-bot-gateway   File: ClientJDA.java   Source Code and License 6 votes vote down vote up
@Override
public void login(String token, ShardInfo shardInfo, SessionReconnectQueue reconnectQueue) throws LoginException, RateLimitedException {
    setStatus(Status.LOGGING_IN);
    if(token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!");

    setToken(token);
    verifyToken();
    this.shardInfo = shardInfo;
    JDAImpl.LOG.info("Login Successful!");

    client = new ClientWebSocketClient(this, reconnectQueue, gatewayClient);
    client.send(new JSONObject()
            .put("d", presence.getFullPresence())
            .put("op", WebSocketCode.PRESENCE).toString());

    if(shutdownHook != null) {
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }
}
 
Example 17
Project: openjdk-jdk10   File: Krb5Util.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the ServiceCreds for the specified server principal from
 * the Subject in the specified AccessControlContext. If not found, and if
 * useSubjectCredsOnly is false, then obtain from a LoginContext.
 *
 * NOTE: This method is also used by JSSE Kerberos Cipher Suites
 */
public static ServiceCreds getServiceCreds(GSSCaller caller,
    String serverPrincipal, AccessControlContext acc)
            throws LoginException {

    Subject accSubj = Subject.getSubject(acc);
    ServiceCreds sc = null;
    if (accSubj != null) {
        sc = ServiceCreds.getInstance(accSubj, serverPrincipal);
    }
    if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        sc = ServiceCreds.getInstance(subject, serverPrincipal);
    }
    return sc;
}
 
Example 18
Project: fcrepo3-security-jaas   File: XmlUsersFileModule.java   Source Code and License 5 votes vote down vote up
@Override
public boolean login() throws LoginException {
    if (debug) {
        logger.debug(this.getClass().getName() + " login called.");
    }

    if (Constants.FEDORA_HOME == null || "".equals(Constants.FEDORA_HOME.trim())) {
        logger.error("FEDORA_HOME constant is not set");
        return false;
    }

    final NameCallback nc = new NameCallback("username");
    final PasswordCallback pc = new PasswordCallback("password", false);
    final Callback[] callbacks = new Callback[] {
            nc, pc
    };

    try {
        handler.handle(callbacks);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new LoginException("IOException occured: " + ioe.getMessage());
    } catch (UnsupportedCallbackException ucbe) {
        ucbe.printStackTrace();
        throw new LoginException("UnsupportedCallbackException encountered: "
                + ucbe.getMessage());
    }

    // Grab the username and password from the callbacks.
    final String username = nc.getName();
    final String password = new String(pc.getPassword());

    successLogin = authenticate(username, password);

    return successLogin;
}
 
Example 19
Project: hadoop   File: TestViewFsHdfs.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void clusterSetupAtBegining() throws IOException,
    LoginException, URISyntaxException {
  SupportsBlocks = true;
  CONF.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true);

  cluster = new MiniDFSCluster.Builder(CONF).numDataNodes(2).build();
  cluster.waitClusterUp();
  fc = FileContext.getFileContext(cluster.getURI(0), CONF);
  Path defaultWorkingDirectory = fc.makeQualified( new Path("/user/" + 
      UserGroupInformation.getCurrentUser().getShortUserName()));
  fc.mkdir(defaultWorkingDirectory, FileContext.DEFAULT_PERM, true);
}
 
Example 20
Project: oscm   File: ADMRealmImplIT.java   Source Code and License 5 votes vote down vote up
@Test
public void handleWebServiceCaller_positive() throws LoginException {

    // given
    long wsPasswordAge = System.currentTimeMillis() - 1;
    String wsPassword = "WS" + wsPasswordAge;

    // then
    realm.handleWebServiceCaller(ANY_KEY, wsPassword);
}
 
Example 21
Project: fcrepo3-security-jaas   File: XmlUsersFileModuleTest.java   Source Code and License 5 votes vote down vote up
public void testParseTwo() throws LoginException {
    assertTrue(module.authenticate("fedoraIntCallUser", "test_changeme"));

    final Map<String, Set<String>> attributes = module.attributes;

    assertTrue(attributes.containsKey("fedoraRole"));
    final Set<String> roles = attributes.get("fedoraRole");
    assertTrue(roles.contains("fedoraInternalCall-1"));
    assertTrue(roles.contains("fedoraInternalCall-2"));
    assertFalse(roles.contains("administrator"));

    assertFalse(attributes.containsKey("custom_one"));
}
 
Example 22
Project: cas-server-4.2.1   File: DefaultAccountStateHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Handle an account state error produced by ldaptive account state machinery.
 * <p>
 * Override this method to provide custom error handling.
 *
 * @param error Account state error.
 * @param response Ldaptive authentication response.
 * @param configuration Password policy configuration.
 * @param messages Container for messages produced by account state error handling.
 *
 * @throws LoginException On errors that should be communicated as login exceptions.
 */
protected void handleError(
        final AccountState.Error error,
        final AuthenticationResponse response,
        final LdapPasswordPolicyConfiguration configuration,
        final List<MessageDescriptor> messages)
        throws LoginException {

    logger.debug("Handling error {}", error);
    final LoginException ex = this.errorMap.get(error);
    if (ex != null) {
        throw ex;
    }
    logger.debug("No LDAP error mapping defined for {}", error);
}
 
Example 23
Project: openjdk-jdk10   File: UnboundSSLUtils.java   Source Code and License 5 votes vote down vote up
static void startServerWithJaas(final SSLEchoServer server,
        String config) throws LoginException, PrivilegedActionException {
    LoginContext context = new LoginContext(config);
    context.login();
    System.out.println("Server: successful authentication");
    Subject.doAs(context.getSubject(),
            (PrivilegedExceptionAction<Object>) () -> {
        SSLEchoServer.startServer(server);
        return null;
    });
}
 
Example 24
Project: springboot-shiro-cas-mybatis   File: DefaultAccountStateHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Handle an account state error produced by ldaptive account state machinery.
 * <p>
 * Override this method to provide custom error handling.
 *
 * @param error Account state error.
 * @param response Ldaptive authentication response.
 * @param configuration Password policy configuration.
 * @param messages Container for messages produced by account state error handling.
 *
 * @throws LoginException On errors that should be communicated as login exceptions.
 */
protected void handleError(
        final AccountState.Error error,
        final AuthenticationResponse response,
        final LdapPasswordPolicyConfiguration configuration,
        final List<MessageDescriptor> messages)
        throws LoginException {

    logger.debug("Handling error {}", error);
    final LoginException ex = this.errorMap.get(error);
    if (ex != null) {
        throw ex;
    }
    logger.debug("No LDAP error mapping defined for {}", error);
}
 
Example 25
Project: lams   File: UniversalLoginModule.java   Source Code and License 5 votes vote down vote up
/**
    * Perform the authentication of the username and password.
    */
   @Override
   public boolean login() throws LoginException {
loginOK = false;
String[] info = getUsernameAndPassword();
String userName = info[0];
String password = info[1];

UniversalLoginModule.log.info("Authenticate user: " + userName);

if (identity == null) {
    try {
	identity = new SimplePrincipal(userName);
    } catch (Exception e) {
	throw new LoginException("Failed to create principal: " + e.getMessage());
    }

    if (!validatePassword(password)) {
	if (UniversalLoginModule.log.isDebugEnabled()) {
	    UniversalLoginModule.log.debug("Bad password for user: " + userName);
	}
	throw new FailedLoginException("Incorrect password");
    }
}

loginOK = true;
if (UniversalLoginModule.log.isDebugEnabled()) {
    UniversalLoginModule.log.debug("User authenticated: " + identity);
}
return true;
   }
 
Example 26
Project: springboot-shiro-cas-mybatis   File: LdapAuthenticationHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<>(this.principalAttributeMap.size());
    for (final Map.Entry<String, String> ldapAttr : this.principalAttributeMap.entrySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttr.getKey());
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = ldapAttr.getValue();
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return this.principalFactory.createPrincipal(id, attributeMap);
}
 
Example 27
Project: cas-5.1.0   File: LdapAuthenticationHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Gets ldap principal identifier. If the principal id attribute is defined, it's retrieved.
 * If no attribute value is found, a warning is generated and the provided username is used instead.
 * If no attribute is defined, username is used instead.
 *
 * @param username  the username
 * @param ldapEntry the ldap entry
 * @return the ldap principal identifier
 * @throws LoginException in case the principal id cannot be determined.
 */
protected String getLdapPrincipalIdentifier(final String username, final LdapEntry ldapEntry) throws LoginException {
    if (StringUtils.isNotBlank(this.principalIdAttribute)) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {

            if (this.allowMissingPrincipalAttributeValue) {
                LOGGER.warn("The principal id attribute [{}] is not found. CAS cannot construct the final authenticated principal "
                                + "if it's unable to locate the attribute that is designated as the principal id. "
                                + "Attributes available on the LDAP entry are [{}]. Since principal id attribute is not available, CAS will "
                                + "fall back to construct the principal based on the provided user id: [{}]",
                        this.principalIdAttribute, ldapEntry.getAttributes(), username);
                return username;
            }
            LOGGER.error("The principal id attribute [{}] is not found. CAS is configured to disallow missing principal attributes",
                    this.principalIdAttribute);
            throw new LoginException("Principal id attribute is not found for " + principalAttr);
        }

        if (principalAttr.size() > 1) {
            if (!this.allowMultiplePrincipalAttributeValues) {
                throw new LoginException("Multiple principal values are not allowed: " + principalAttr);
            }
            LOGGER.warn("Found multiple values for principal id attribute: [{}]. Using first value=[{}].", principalAttr, principalAttr.getStringValue());
        }
        LOGGER.debug("Retrieved principal id attribute [{}]", principalAttr.getStringValue());
        return principalAttr.getStringValue();
    }

    LOGGER.debug("Principal id attribute is not defined. Using the default provided user id [{}]", username);
    return username;
}
 
Example 28
Project: unitimes   File: DbAuthenticateModule.java   Source Code and License 5 votes vote down vote up
/**
 * Abort authentication (when overall authentication fails)
 */
public boolean abort() throws LoginException {
	if (!isAuthSucceeded()) {
		return false;
	} else {
		if (isAuthSucceeded() && !isCommitSucceeded()) {
			reset();
		} else {
			logout();
		}
	}

	return true;
}
 
Example 29
Project: Phonon   File: DiscordBot.java   Source Code and License 5 votes vote down vote up
public void onEnable(Phonon phononPlugin) {
    if (phononPlugin.getConfigAdapter(CoreModule.ID, CoreConfigAdapter.class).isPresent()) {
        CoreConfig config = phononPlugin.getConfigAdapter(CoreModule.ID, CoreConfigAdapter.class).get().getNodeOrDefault();
        String token = config.getToken();
        if (config.getPrefix().equals("/")) {
            phononPlugin.getLogger().warn("Using '/' as a command prefix is highly discouraged.");
        }

        codes = new HashMap<>();
        try {
            if (config.getToken().isEmpty()) {
                return;
            }
            jda = new JDABuilder(AccountType.BOT)
                    .setToken(token)
                    .setAudioEnabled(false)
                    .setAutoReconnect(true)
                    .setEnableShutdownHook(true)
                    .buildAsync();
            if (!config.getGame().isEmpty()) {
                jda.getPresence().setGame(Game.of(config.getGame()));
            }
            jda.addEventListener(new CommandListener(phononPlugin));
        } catch (LoginException | RateLimitedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 30
Project: hadoop   File: TestViewFileSystemAtHdfsRoot.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void clusterSetupAtBegining() throws IOException,
    LoginException, URISyntaxException {
  SupportsBlocks = true;
  CONF.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true);
  
  cluster = new MiniDFSCluster.Builder(CONF)
    .numDataNodes(2)
    .build();
  cluster.waitClusterUp();
  
  fHdfs = cluster.getFileSystem();
}
 
Example 31
Project: hadoop-oss   File: UserGroupInformation.java   Source Code and License 5 votes vote down vote up
@Override
public boolean logout() throws LoginException {
  if (LOG.isDebugEnabled()) {
    LOG.debug("hadoop logout");
  }
  return true;
}
 
Example 32
Project: keycloak-remote-ejb   File: ConvertKeycloakRolesLoginModule.java   Source Code and License 5 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    Set<RolePrincipal> kcRoles = subject.getPrincipals(RolePrincipal.class);
    logger.info("commit invoked. Keycloak roles: " + kcRoles);

    SimpleGroup wfRoles = new SimpleGroup("Roles");
    for (RolePrincipal kcRole : kcRoles) {
        wfRoles.addMember(new SimplePrincipal(kcRole.getName()));
    }

    subject.getPrincipals().add(wfRoles);

    return true;
}
 
Example 33
Project: jdk8u-jdk   File: LCTest.java   Source Code and License 5 votes vote down vote up
@Override
public boolean abort() throws LoginException {
    LCTest.logAction("abort");
    if (succeeded == false) {
        return false;
    }
    clearState();
    return true;
}
 
Example 34
Project: kafka-0.11.0.0-src-with-comment   File: LoginManager.java   Source Code and License 5 votes vote down vote up
private LoginManager(JaasContext jaasContext, boolean hasKerberos, Map<String, ?> configs,
                     Password jaasConfigValue) throws IOException, LoginException {
    this.cacheKey = jaasConfigValue != null ? jaasConfigValue : jaasContext.name();
    login = hasKerberos ? new KerberosLogin() : new DefaultLogin();
    login.configure(configs, jaasContext);
    login.login();
}
 
Example 35
Project: jdk8u-jdk   File: Krb5Util.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the caller's Subject, or Subject obtained by logging in
 * via the specified caller.
 *
 * Caller must have permission to:
 *    - access the Subject
 *    - create LoginContext
 *    - read the auth.login.defaultCallbackHandler security property
 *
 * NOTE: This method is used by JSSE Kerberos Cipher Suites
 */
public static Subject getSubject(GSSCaller caller,
    AccessControlContext acc) throws LoginException {

    // Try to get the Subject from acc
    Subject subject = Subject.getSubject(acc);

    // Try to get Subject obtained from GSSUtil
    if (subject == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
    }
    return subject;
}
 
Example 36
Project: lams   File: UniversalLoginModule.java   Source Code and License 5 votes vote down vote up
/**
    * Remove the user identity and roles added to the Subject during commit.
    *
    * @return true always.
    */
   @Override
   public boolean logout() throws LoginException {
UniversalLoginModule.log.info("User logged out: " + getUserName());
// Remove the user identity
Set<Principal> principals = subject.getPrincipals();
principals.remove(identity);
return true;
   }
 
Example 37
Project: jdk8u-jdk   File: Krb5ProxyImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Object getServiceCreds(AccessControlContext acc)
        throws LoginException {
    ServiceCreds serviceCreds =
        Krb5Util.getServiceCreds(GSSCaller.CALLER_SSL_SERVER, null, acc);
    return serviceCreds;
}
 
Example 38
Project: neoscada   File: LoginModule.java   Source Code and License 5 votes vote down vote up
@Override
public boolean commit () throws LoginException
{
    this.subject.getPrincipals ().add ( new UserInformationPrincipal ( this.userInformation ) );
    this.subject.getPublicCredentials ().add ( this.userInformation );
    return this.loggedIn;
}
 
Example 39
Project: oscm   File: EJBServiceAccess.java   Source Code and License 5 votes vote down vote up
private void ejbLogin(long key, String password) throws LoginException {
    final SecurityService securityService = SystemInstance.get()
            .getComponent(SecurityService.class);
    final Object token;
        securityService.disassociate();

        token = securityService.login(
                Long.valueOf(key).toString(),
                password);
        if (AbstractSecurityService.class.isInstance(securityService)
                && AbstractSecurityService.class.cast(securityService)
                .currentState() == null) {
            securityService.associate(token);
        }
}
 
Example 40
Project: GuildBot   File: GuildBot.java   Source Code and License 5 votes vote down vote up
public GuildBot(final File config, final String token, final String webhookURL) throws LoginException, IllegalArgumentException, RateLimitedException, FileNotFoundException, IOException
{
    this.config = JsonValue.readHjson(FileUtils.readFileToString(config, "UTF-8")).asObject();

    this.threadPool = new ScheduledThreadPoolExecutor(4, r ->
    {
        final Thread t = new Thread(r, "GuildBot-" + GuildBot.threadCounter.getAndIncrement());
        t.setUncaughtExceptionHandler((thread, throwable) ->
        {
            GuildBot.log.error("An error occurred", throwable);
            handleThrowable(throwable, "Uncaught error in thread: " + thread.getName());
        });
        return t;
    });
    this.threadPool.setKeepAliveTime(1, TimeUnit.MINUTES);

    this.webhook = webhookURL == null
            ? null
            : new WebhookClientBuilder(webhookURL)
            .setExecutorService(threadPool)
            .setDaemon(true)
            .setThreadFactory(r -> new Thread(r, "Error-Webhook-Thread"))
            .build();

    final JDABuilder builder = new JDABuilder(AccountType.BOT);

    builder.setEventManager(new AnnotatedEventManager());

    builder.setToken(token);

    builder.setGame(Game.of("loading..."));
    builder.setStatus(OnlineStatus.DO_NOT_DISTURB);

    builder.addEventListener(this);

    this.jda = builder.buildAsync();
}