Java Code Examples for javax.security.auth.callback.CallbackHandler

The following are top voted examples for showing how to use javax.security.auth.callback.CallbackHandler. 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: fcrepo3-security-jaas   File: XmlUsersFileModule.java   View source code 7 votes vote down vote up
@Override
public void initialize(Subject subject,
        CallbackHandler handler,
        Map<String, ?> sharedState,
        Map<String, ?> options) {
    this.subject = subject;
    this.handler = handler;
    this.options = options;

    String debugOption = (String) this.options.get("debug");
    if (debugOption != null && "true".equalsIgnoreCase(debugOption)) {
        debug = true;
    }

    attributes = new HashMap<String, Set<String>>();

    if (debug) {
        logger.debug("login module initialised: {}", this.getClass().getName());
    }
}
 
Example 2
Project: lams   File: JAASMemoryLoginModule.java   View source code 7 votes vote down vote up
/**
 * Initialize this <code>LoginModule</code> with the specified
 * configuration information.
 *
 * @param subject The <code>Subject</code> to be authenticated
 * @param callbackHandler A <code>CallbackHandler</code> for communicating
 *  with the end user as necessary
 * @param sharedState State information shared with other
 *  <code>LoginModule</code> instances
 * @param options Configuration information for this specific
 *  <code>LoginModule</code> instance
 */
public void initialize(Subject subject, CallbackHandler callbackHandler,
                       Map sharedState, Map options) {
    log.debug("Init");

    // Save configuration values
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;

    // Perform instance-specific initialization
    if (options.get("pathname") != null)
        this.pathname = (String) options.get("pathname");

    // Load our defined Principals
    load();

}
 
Example 3
Project: openjdk-jdk10   File: GSSUtil.java   View source code 7 votes vote down vote up
/**
 * Authenticate using the login module from the specified
 * configuration entry.
 *
 * @param caller the caller of JAAS Login
 * @param mech the mech to be used
 * @return the authenticated subject
 */
public static Subject login(GSSCaller caller, Oid mech) throws LoginException {

    CallbackHandler cb = null;
    if (caller instanceof HttpCaller) {
        cb = new sun.net.www.protocol.http.spnego.NegotiateCallbackHandler(
                ((HttpCaller)caller).info());
    } else {
        String defaultHandler =
                java.security.Security.getProperty(DEFAULT_HANDLER);
        // get the default callback handler
        if ((defaultHandler != null) && (defaultHandler.length() != 0)) {
            cb = null;
        } else {
            cb = new ConsoleCallbackHandler();
        }
    }

    // New instance of LoginConfigImpl must be created for each login,
    // since the entry name is not passed as the first argument, but
    // generated with caller and mech inside LoginConfigImpl
    LoginContext lc = new LoginContext("", null, cb,
            new LoginConfigImpl(caller, mech));
    lc.login();
    return lc.getSubject();
}
 
Example 4
Project: jdk8u-jdk   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the DIGEST-MD5 SASL client mechanism.
 *
 * @throws SaslException If there is an error creating the DigestMD5
 * SASL client.
 * @returns a new SaslClient ; otherwise null if unsuccessful.
 */
public SaslClient createSaslClient(String[] mechs,
     String authorizationId, String protocol, String serverName,
     Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     for (int i=0; i<mechs.length; i++) {
        if (mechs[i].equals(myMechs[DIGEST_MD5]) &&
            PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for RealmChoiceCallback, " +
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }

            return new DigestMD5Client(authorizationId,
                protocol, serverName, props, cbh);
        }
    }
    return null;
}
 
Example 5
Project: jmeter-wssecurity   File: WSSDecryptionPostProcessor.java   View source code 6 votes vote down vote up
@Override
protected Document process(Document document) throws WSSecurityException {
    WSSecurityEngine secEngine = new WSSecurityEngine();

    WSHandlerResult results = secEngine.processSecurityHeader(document, null, 
        new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof WSPasswordCallback) {
                        ((WSPasswordCallback)callback).setPassword(getCertPassword());
                    }
                }
            }
        }, getCrypto());

    return document;
}
 
Example 6
Project: openjdk-jdk10   File: DynamicConfigurationTest.java   View source code 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 7
Project: openjdk-jdk10   File: KeyStoreLoginModule.java   View source code 6 votes vote down vote up
/**
 * Initialize this {@code LoginModule}.
 *
 * @param subject the {@code Subject} to be authenticated.
 *
 * @param callbackHandler a {@code CallbackHandler} for communicating
 *                  with the end user (prompting for usernames and
 *                  passwords, for example),
 *                  which may be {@code null}.
 *
 * @param sharedState shared {@code LoginModule} state.
 *
 * @param options options specified in the login
 *                  {@code Configuration} for this particular
 *                  {@code LoginModule}.
 */
// Unchecked warning from (Map<String, Object>)sharedState is safe
// since javax.security.auth.login.LoginContext passes a raw HashMap.
@SuppressWarnings("unchecked")
public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map<String,?> sharedState,
                       Map<String,?> options)
{
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = (Map<String, Object>)sharedState;
    this.options = options;

    processOptions();
    status = INITIALIZED;
}
 
Example 8
Project: jdk8u-jdk   File: LoginModuleOptions.java   View source code 6 votes vote down vote up
static void login(CallbackHandler callback, Object... options)
        throws Exception {
    Krb5LoginModule krb5 = new Krb5LoginModule();
    Subject subject = new Subject();
    Map<String, String> map = new HashMap<>();
    Map<String, Object> shared = new HashMap<>();

    int count = options.length / 2;
    for (int i = 0; i < count; i++) {
        String key = (String) options[2 * i];
        Object value = options[2 * i + 1];
        if (key.startsWith("javax")) {
            shared.put(key, value);
        } else {
            map.put(key, (String) value);
        }
    }
    krb5.initialize(subject, callback, shared, map);
    krb5.login();
    krb5.commit();
    if (!subject.getPrincipals().iterator().next()
            .getName().startsWith(OneKDC.USER)) {
        throw new Exception("The authenticated is not " + OneKDC.USER);
    }
}
 
Example 9
Project: tomcat7   File: JAASMemoryLoginModule.java   View source code 6 votes vote down vote up
/**
 * Initialize this <code>LoginModule</code> with the specified
 * configuration information.
 *
 * @param subject The <code>Subject</code> to be authenticated
 * @param callbackHandler A <code>CallbackHandler</code> for communicating
 *  with the end user as necessary
 * @param sharedState State information shared with other
 *  <code>LoginModule</code> instances
 * @param options Configuration information for this specific
 *  <code>LoginModule</code> instance
 */
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
                       Map<String,?> sharedState, Map<String,?> options) {
    log.debug("Init");

    // Save configuration values
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;

    // Perform instance-specific initialization
    if (options.get("pathname") != null)
        this.pathname = (String) options.get("pathname");

    // Load our defined Principals
    load();

}
 
Example 10
Project: jdk8u-jdk   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the DIGEST-MD5 SASL server mechanism.
 *
 * @throws SaslException If there is an error creating the DigestMD5
 * SASL server.
 * @returns a new SaslServer ; otherwise null if unsuccessful.
 */
public SaslServer createSaslServer(String mech,
     String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     if (mech.equals(myMechs[DIGEST_MD5]) &&
         PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for AuthorizeCallback, "+
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }

            return new DigestMD5Server(protocol, serverName, props, cbh);
     }
     return null;
}
 
Example 11
Project: jdk8u-jdk   File: DigestMD5Client.java   View source code 6 votes vote down vote up
/**
   * Constructor for DIGEST-MD5 mechanism.
   *
   * @param authzid A non-null String representing the principal
   * for which authorization is being granted..
   * @param digestURI A non-null String representing detailing the
   * combined protocol and host being used for authentication.
   * @param props The possibly null properties to be used by the SASL
   * mechanism to configure the authentication exchange.
   * @param cbh The non-null CallbackHanlder object for callbacks
   * @throws SaslException if no authentication ID or password is supplied
   */
 DigestMD5Client(String authzid, String protocol, String serverName,
     Map<String, ?> props, CallbackHandler cbh) throws SaslException {

     super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh);

     // authzID can only be encoded in UTF8 - RFC 2222
     if (authzid != null) {
         this.authzid = authzid;
         try {
             authzidBytes = authzid.getBytes("UTF8");

         } catch (UnsupportedEncodingException e) {
             throw new SaslException(
                 "DIGEST-MD5: Error encoding authzid value into UTF-8", e);
         }
     }

     if (props != null) {
         specifiedCipher = (String)props.get(CIPHER_PROPERTY);

         logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}",
             specifiedCipher);
     }
}
 
Example 12
Project: openjdk-jdk10   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the DIGEST-MD5 SASL client mechanism.
 *
 * @throws SaslException If there is an error creating the DigestMD5
 * SASL client.
 * @return a new SaslClient; otherwise null if unsuccessful.
 */
public SaslClient createSaslClient(String[] mechs,
     String authorizationId, String protocol, String serverName,
     Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     for (int i=0; i<mechs.length; i++) {
        if (mechs[i].equals(myMechs[DIGEST_MD5]) &&
            PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for RealmChoiceCallback, " +
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }

            return new DigestMD5Client(authorizationId,
                protocol, serverName, props, cbh);
        }
    }
    return null;
}
 
Example 13
Project: openjdk-jdk10   File: DigestMD5Client.java   View source code 6 votes vote down vote up
/**
   * Constructor for DIGEST-MD5 mechanism.
   *
   * @param authzid A non-null String representing the principal
   * for which authorization is being granted..
   * @param digestURI A non-null String representing detailing the
   * combined protocol and host being used for authentication.
   * @param props The possibly null properties to be used by the SASL
   * mechanism to configure the authentication exchange.
   * @param cbh The non-null CallbackHanlder object for callbacks
   * @throws SaslException if no authentication ID or password is supplied
   */
 DigestMD5Client(String authzid, String protocol, String serverName,
     Map<String, ?> props, CallbackHandler cbh) throws SaslException {

     super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh);

     // authzID can only be encoded in UTF8 - RFC 2222
     if (authzid != null) {
         this.authzid = authzid;
         try {
             authzidBytes = authzid.getBytes("UTF8");

         } catch (UnsupportedEncodingException e) {
             throw new SaslException(
                 "DIGEST-MD5: Error encoding authzid value into UTF-8", e);
         }
     }

     if (props != null) {
         specifiedCipher = (String)props.get(CIPHER_PROPERTY);

         logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}",
             specifiedCipher);
     }
}
 
Example 14
Project: OpenJSharp   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the NTLM SASL server mechanism.
 * Argument checks are performed in SaslServer's constructor.
 * @returns a new SaslServer ; otherwise null if unsuccessful.
 * @throws SaslException If there is an error creating the NTLM
 * SASL server.
 */
public SaslServer createSaslServer(String mech,
     String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     if (mech.equals("NTLM") &&
             PolicyUtils.checkPolicy(mechPolicies[0], props)) {
         if (props != null) {
             String qop = (String)props.get(Sasl.QOP);
             if (qop != null && !qop.equals("auth")) {
                 throw new SaslException("NTLM only support auth");
             }
         }
         if (cbh == null) {
             throw new SaslException(
                 "Callback handler with support for " +
                 "RealmCallback, NameCallback, and PasswordCallback " +
                 "required");
         }
         return new NTLMServer(mech, protocol, serverName, props, cbh);
     }
     return null;
}
 
Example 15
Project: openjdk-jdk10   File: FactoryImpl.java   View source code 6 votes vote down vote up
public SaslClient createSaslClient(String[] mechs,
    String authorizationId,
    String protocol,
    String serverName,
    Map<String,?> props,
    CallbackHandler cbh) throws SaslException {

        for (int i = 0; i < mechs.length; i++) {
            if (mechs[i].equals(myMechs[GSS_KERB_V5])
                && PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
                return new GssKrb5Client(
                    authorizationId,
                    protocol,
                    serverName,
                    props,
                    cbh);
            }
        }
        return null;
}
 
Example 16
Project: openjdk-jdk10   File: P11KeyStore.java   View source code 6 votes vote down vote up
private void login(CallbackHandler handler) throws LoginException {
    if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {
        token.provider.login(null, handler);
    } else {
        // token supports protected authentication path
        // (external pin-pad, for example)
        if (handler != null &&
            !token.config.getKeyStoreCompatibilityMode()) {
            throw new LoginException("can not specify password if token " +
                            "supports protected authentication path");
        }

        // must rely on application-set or default handler
        // if one is necessary
        token.provider.login(null, null);
    }
}
 
Example 17
Project: OpenJSharp   File: DigestMD5Client.java   View source code 6 votes vote down vote up
/**
   * Constructor for DIGEST-MD5 mechanism.
   *
   * @param authzid A non-null String representing the principal
   * for which authorization is being granted..
   * @param digestURI A non-null String representing detailing the
   * combined protocol and host being used for authentication.
   * @param props The possibly null properties to be used by the SASL
   * mechanism to configure the authentication exchange.
   * @param cbh The non-null CallbackHanlder object for callbacks
   * @throws SaslException if no authentication ID or password is supplied
   */
 DigestMD5Client(String authzid, String protocol, String serverName,
     Map<String, ?> props, CallbackHandler cbh) throws SaslException {

     super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh);

     // authzID can only be encoded in UTF8 - RFC 2222
     if (authzid != null) {
         this.authzid = authzid;
         try {
             authzidBytes = authzid.getBytes("UTF8");

         } catch (UnsupportedEncodingException e) {
             throw new SaslException(
                 "DIGEST-MD5: Error encoding authzid value into UTF-8", e);
         }
     }

     if (props != null) {
         specifiedCipher = (String)props.get(CIPHER_PROPERTY);

         logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}",
             specifiedCipher);
     }
}
 
Example 18
Project: OpenJSharp   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the DIGEST-MD5 SASL client mechanism.
 *
 * @throws SaslException If there is an error creating the DigestMD5
 * SASL client.
 * @returns a new SaslClient ; otherwise null if unsuccessful.
 */
public SaslClient createSaslClient(String[] mechs,
     String authorizationId, String protocol, String serverName,
     Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     for (int i=0; i<mechs.length; i++) {
        if (mechs[i].equals(myMechs[DIGEST_MD5]) &&
            PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for RealmChoiceCallback, " +
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }

            return new DigestMD5Client(authorizationId,
                protocol, serverName, props, cbh);
        }
    }
    return null;
}
 
Example 19
Project: lazycat   File: JAASMemoryLoginModule.java   View source code 6 votes vote down vote up
/**
 * Initialize this <code>LoginModule</code> with the specified configuration
 * information.
 *
 * @param subject
 *            The <code>Subject</code> to be authenticated
 * @param callbackHandler
 *            A <code>CallbackHandler</code> for communicating with the end
 *            user as necessary
 * @param sharedState
 *            State information shared with other <code>LoginModule</code>
 *            instances
 * @param options
 *            Configuration information for this specific
 *            <code>LoginModule</code> instance
 */
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
		Map<String, ?> options) {
	log.debug("Init");

	// Save configuration values
	this.subject = subject;
	this.callbackHandler = callbackHandler;
	this.sharedState = sharedState;
	this.options = options;

	// Perform instance-specific initialization
	if (options.get("pathname") != null)
		this.pathname = (String) options.get("pathname");

	// Load our defined Principals
	load();

}
 
Example 20
Project: openjdk-jdk10   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the NTLM SASL client mechanism.
 * Argument checks are performed in SaslClient's constructor.
 * @return a new SaslClient; otherwise null if unsuccessful.
 * @throws SaslException If there is an error creating the NTLM
 * SASL client.
 */
public SaslClient createSaslClient(String[] mechs,
     String authorizationId, String protocol, String serverName,
     Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     for (int i=0; i<mechs.length; i++) {
        if (mechs[i].equals("NTLM") &&
                PolicyUtils.checkPolicy(mechPolicies[0], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for " +
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }
            return new NTLMClient(mechs[i], authorizationId,
                protocol, serverName, props, cbh);
        }
    }
    return null;
}
 
Example 21
Project: jdk8u-jdk   File: DynamicConfigurationTest.java   View source code 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 22
Project: apache-tomcat-7.0.73-with-comment   File: JAASMemoryLoginModule.java   View source code 6 votes vote down vote up
/**
 * Initialize this <code>LoginModule</code> with the specified
 * configuration information.
 *
 * @param subject The <code>Subject</code> to be authenticated
 * @param callbackHandler A <code>CallbackHandler</code> for communicating
 *  with the end user as necessary
 * @param sharedState State information shared with other
 *  <code>LoginModule</code> instances
 * @param options Configuration information for this specific
 *  <code>LoginModule</code> instance
 */
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
                       Map<String,?> sharedState, Map<String,?> options) {
    log.debug("Init");

    // Save configuration values
    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;

    // Perform instance-specific initialization
    if (options.get("pathname") != null)
        this.pathname = (String) options.get("pathname");

    // Load our defined Principals
    load();

}
 
Example 23
Project: hadoop   File: SaslDataTransferClient.java   View source code 6 votes vote down vote up
/**
 * Sends client SASL negotiation for specialized encrypted handshake.
 *
 * @param underlyingOut connection output stream
 * @param underlyingIn connection input stream
 * @param encryptionKey for an encrypted SASL handshake
 * @return new pair of streams, wrapped after SASL negotiation
 * @throws IOException for any error
 */
private IOStreamPair getEncryptedStreams(OutputStream underlyingOut,
    InputStream underlyingIn, DataEncryptionKey encryptionKey)
    throws IOException {
  Map<String, String> saslProps = createSaslPropertiesForEncryption(
    encryptionKey.encryptionAlgorithm);

  LOG.debug("Client using encryption algorithm {}",
    encryptionKey.encryptionAlgorithm);

  String userName = getUserNameFromEncryptionKey(encryptionKey);
  char[] password = encryptionKeyToPassword(encryptionKey.encryptionKey);
  CallbackHandler callbackHandler = new SaslClientCallbackHandler(userName,
    password);
  return doSaslHandshake(underlyingOut, underlyingIn, userName, saslProps,
    callbackHandler);
}
 
Example 24
Project: jdk8u-jdk   File: FactoryImpl.java   View source code 6 votes vote down vote up
public SaslServer createSaslServer(String mech,
    String protocol,
    String serverName,
    Map<String,?> props,
    CallbackHandler cbh) throws SaslException {
        if (mech.equals(myMechs[GSS_KERB_V5])
            && PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
            if (cbh == null) {
                throw new SaslException(
            "Callback handler with support for AuthorizeCallback required");
            }
            return new GssKrb5Server(
                protocol,
                serverName,
                props,
                cbh);
        }
        return null;
}
 
Example 25
Project: hadoop   File: SaslRpcServer.java   View source code 6 votes vote down vote up
@Override
public SaslServer createSaslServer(String mechanism, String protocol,
    String serverName, Map<String,?> props, CallbackHandler cbh)
    throws SaslException {
  SaslServer saslServer = null;
  List<SaslServerFactory> factories = factoryCache.get(mechanism);
  if (factories != null) {
    for (SaslServerFactory factory : factories) {
      saslServer = factory.createSaslServer(
          mechanism, protocol, serverName, props, cbh);
      if (saslServer != null) {
        break;
      }
    }
  }
  return saslServer;
}
 
Example 26
Project: hadoop   File: TestSaslRPC.java   View source code 6 votes vote down vote up
private void runNegotiation(CallbackHandler clientCbh,
                            CallbackHandler serverCbh)
                                throws SaslException {
  String mechanism = AuthMethod.PLAIN.getMechanismName();

  SaslClient saslClient = Sasl.createSaslClient(
      new String[]{ mechanism }, null, null, null, null, clientCbh);
  assertNotNull(saslClient);

  SaslServer saslServer = Sasl.createSaslServer(
      mechanism, null, "localhost", null, serverCbh);
  assertNotNull("failed to find PLAIN server", saslServer);
  
  byte[] response = saslClient.evaluateChallenge(new byte[0]);
  assertNotNull(response);
  assertTrue(saslClient.isComplete());

  response = saslServer.evaluateResponse(response);
  assertNull(response);
  assertTrue(saslServer.isComplete());
  assertNotNull(saslServer.getAuthorizationID());
}
 
Example 27
Project: kafka-0.11.0.0-src-with-comment   File: ScramSaslClient.java   View source code 6 votes vote down vote up
@Override
public SaslClient createSaslClient(String[] mechanisms,
        String authorizationId,
        String protocol,
        String serverName,
        Map<String, ?> props,
        CallbackHandler cbh) throws SaslException {

    ScramMechanism mechanism = null;
    for (String mech : mechanisms) {
        mechanism = ScramMechanism.forMechanismName(mech);
        if (mechanism != null)
            break;
    }
    if (mechanism == null)
        throw new SaslException(String.format("Requested mechanisms '%s' not supported. Supported mechanisms are '%s'.",
                Arrays.asList(mechanisms), ScramMechanism.mechanismNames()));

    try {
        return new ScramSaslClient(mechanism, cbh);
    } catch (NoSuchAlgorithmException e) {
        throw new SaslException("Hash algorithm not supported for mechanism " + mechanism, e);
    }
}
 
Example 28
Project: jdk8u-jdk   File: P11KeyStore.java   View source code 6 votes vote down vote up
private void login(CallbackHandler handler) throws LoginException {
    if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {
        token.provider.login(null, handler);
    } else {
        // token supports protected authentication path
        // (external pin-pad, for example)
        if (handler != null &&
            !token.config.getKeyStoreCompatibilityMode()) {
            throw new LoginException("can not specify password if token " +
                            "supports protected authentication path");
        }

        // must rely on application-set or default handler
        // if one is necessary
        token.provider.login(null, null);
    }
}
 
Example 29
Project: jdk8u-jdk   File: FactoryImpl.java   View source code 6 votes vote down vote up
/**
 * Returns a new instance of the NTLM SASL client mechanism.
 * Argument checks are performed in SaslClient's constructor.
 * @returns a new SaslClient ; otherwise null if unsuccessful.
 * @throws SaslException If there is an error creating the NTLM
 * SASL client.
 */
public SaslClient createSaslClient(String[] mechs,
     String authorizationId, String protocol, String serverName,
     Map<String,?> props, CallbackHandler cbh)
     throws SaslException {

     for (int i=0; i<mechs.length; i++) {
        if (mechs[i].equals("NTLM") &&
                PolicyUtils.checkPolicy(mechPolicies[0], props)) {

            if (cbh == null) {
                throw new SaslException(
                    "Callback handler with support for " +
                    "RealmCallback, NameCallback, and PasswordCallback " +
                    "required");
            }
            return new NTLMClient(mechs[i], authorizationId,
                protocol, serverName, props, cbh);
        }
    }
    return null;
}
 
Example 30
Project: jdk8u-jdk   File: FactoryImpl.java   View source code 6 votes vote down vote up
public SaslClient createSaslClient(String[] mechs,
    String authorizationId,
    String protocol,
    String serverName,
    Map<String,?> props,
    CallbackHandler cbh) throws SaslException {

        for (int i = 0; i < mechs.length; i++) {
            if (mechs[i].equals(myMechs[GSS_KERB_V5])
                && PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
                return new GssKrb5Client(
                    authorizationId,
                    protocol,
                    serverName,
                    props,
                    cbh);
            }
        }
        return null;
}
 
Example 31
Project: mi-firma-android   File: Tif.java   View source code 5 votes vote down vote up
/** Construye una tarjeta FNMT TIF (variante del DNIe).
    * @param conn Conexi&oacute;n con la tarjeta.
    * @param pwc <i>PasswordCallback</i> para obtener el PIN de la TIF.
    * @param cryptoHelper Funcionalidades criptogr&aacute;ficas de utilidad que pueden variar entre m&aacute;quinas virtuales.
    * @param ch Gestor de <i>callbacks</i> para la solicitud de datos al usuario.
    * @throws ApduConnectionException Si la conexi&oacute;n con la tarjeta se proporciona cerrada y no es posible abrirla.*/
public Tif(final ApduConnection conn,
		   final PasswordCallback pwc,
		   final CryptoHelper cryptoHelper,
		   final CallbackHandler ch) throws ApduConnectionException {
	super(conn, pwc, cryptoHelper, ch);
}
 
Example 32
Project: kerberos-docker   File: Jaas.java   View source code 5 votes vote down vote up
public static void loginAndAction(String name, PrivilegedExceptionAction action)
    throws LoginException, PrivilegedActionException {

  // Create a callback handler
  CallbackHandler callbackHandler = new TextCallbackHandler();

  LoginContext context = null;

  try {
    // Create a LoginContext with a callback handler
    context = new LoginContext(name, callbackHandler);

    // Perform authentication
    context.login();
  } catch (LoginException e) {
    System.err.println("Login failed");
    e.printStackTrace();
    System.exit(-1);
  }

  // Perform action as authenticated user
  Subject subject = context.getSubject();
  if (verbose) {
    System.out.println(subject.toString());
  } else {
    System.out.println("Authenticated principal: " + subject.getPrincipals());
  }

  Subject.doAs(subject, action);

  context.logout();
}
 
Example 33
Project: neoscada   File: LoginModule.java   View source code 5 votes vote down vote up
@SuppressWarnings ( "rawtypes" )
@Override
public void initialize ( final Subject subject, final CallbackHandler callbackHandler, final Map sharedState, final Map options )
{
    this.subject = subject;
    this.callbackHandler = callbackHandler;
}
 
Example 34
Project: message-broker   File: PlainSaslServerFactory.java   View source code 5 votes vote down vote up
@Override
public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
        CallbackHandler cbh) throws SaslException {
    if (!(cbh instanceof PlainSaslCallbackHandler)) {
        throw new SaslException(
                "CallbackHandler must be of type of PlainSaslCallbackHandler, but received  : " + cbh
                        .getClass());
    }
    return (PlainSaslServer.PLAIN_MECHANISM.equals(mechanism)) ?
            new PlainSaslServer((PlainSaslCallbackHandler) cbh) :
            null;
}
 
Example 35
Project: jdk8u-jdk   File: CustomLoginModule.java   View source code 5 votes vote down vote up
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
        Map<String, ?> sharedState, Map<String, ?> options) {
    this.subject = subject;
    this.callbackHandler = callbackHandler;

    // check if custom parameter is passed from comfiguration
    if (options == null) {
        throw new RuntimeException("options is null");
    }

    // read username/password from configuration
    Object o = options.get("username");
    if (o == null) {
        throw new RuntimeException("Custom parameter not passed");
    }
    if (!(o instanceof String)) {
        throw new RuntimeException("Password is not a string");
    }
    username = (String) o;

    o = options.get("password");
    if (o == null) {
        throw new RuntimeException("Custom parameter not passed");
    }
    if (!(o instanceof String)) {
        throw new RuntimeException("Password is not a string");
    }
    password = ((String) o).toCharArray();
}
 
Example 36
Project: mi-firma-android   File: DnieNFC.java   View source code 5 votes vote down vote up
DnieNFC(final ApduConnection conn,
		final PasswordCallback pwc,
		final CryptoHelper cryptoHelper,
		final CallbackHandler ch) throws ApduConnectionException,
                                    PaceException {
	super(paceConnection(conn, ch), pwc, cryptoHelper, ch);
}
 
Example 37
Project: taskana   File: SampleLoginModule.java   View source code 5 votes vote down vote up
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
		Map<String, ?> options) {

	try {
		NameCallback nameCallback = new NameCallback("prompt");
		PasswordCallback passwordCallback = new PasswordCallback("prompt", false);

		callbackHandler.handle(new Callback[] { nameCallback, passwordCallback });
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 38
Project: ARCLib   File: PasswordTicketValidator.java   View source code 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.servicePrincipal, "servicePrincipal must be specified");
    LoginConfig loginConfig = new LoginConfig(this.servicePrincipal, this.debug, isInitiator);
    Set<Principal> princ = new HashSet<>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<>(), new HashSet<>());

    final CallbackHandler handler = getUsernamePasswordHandler(servicePrincipal, password);

    LoginContext lc = new LoginContext("", sub, handler, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}
 
Example 39
Project: ARCLib   File: PasswordTicketValidator.java   View source code 5 votes vote down vote up
private static CallbackHandler getUsernamePasswordHandler(final String username, final String password) {
    return callbacks -> {
        for (Callback callback : callbacks) {
            if (callback instanceof NameCallback) {
                final NameCallback nameCallback = (NameCallback) callback;
                nameCallback.setName(username);
            } else if (callback instanceof PasswordCallback) {
                final PasswordCallback passCallback = (PasswordCallback) callback;
                passCallback.setPassword(password.toCharArray());
            } else {
                System.err.println("Unsupported Callback: " + callback.getClass().getName());
            }
        }
    };
}
 
Example 40
Project: openjdk-jdk10   File: ConfigConstructor.java   View source code 5 votes vote down vote up
public void initialize(Subject s, CallbackHandler ch,
        Map<String,?> state, Map<String,?> options) {
    if (s == ConfigConstructor.s ||
        ch != null) {
        throw new SecurityException("Module 2 failed");
    }
}