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

The following examples show how to use javax.security.auth.callback.CallbackHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Tomcat8-Source-Read   Source File: AuthenticatorBase.java    License: MIT License 6 votes vote down vote up
private JaspicState getJaspicState(AuthConfigProvider jaspicProvider, Request request,
        Response response, boolean authMandatory) throws IOException {
    JaspicState jaspicState = new JaspicState();

    jaspicState.messageInfo =
            new MessageInfoImpl(request.getRequest(), response.getResponse(), authMandatory);

    try {
        CallbackHandler callbackHandler = createCallbackHandler();
        ServerAuthConfig serverAuthConfig = jaspicProvider.getServerAuthConfig(
                "HttpServlet", jaspicAppContextID, callbackHandler);
        String authContextID = serverAuthConfig.getAuthContextID(jaspicState.messageInfo);
        jaspicState.serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
    } catch (AuthException e) {
        log.warn(sm.getString("authenticator.jaspicServerAuthContextFail"), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    return jaspicState;
}
 
Example 2
Source Project: openjdk-jdk8u   Source File: FactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a new instance of the NTLM SASL server mechanism.
 * Argument checks are performed in SaslServer's constructor.
 * @return 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 3
Source Project: jdk8u60   Source File: FactoryImpl.java    License: GNU General Public License v2.0 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 4
Source Project: Bats   Source File: FastSaslClientFactory.java    License: Apache License 2.0 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 {
  for (final String mechanism : mechanisms) {
    final List<SaslClientFactory> factories = clientFactories.get(mechanism);
    if (factories != null) {
      for (final SaslClientFactory factory : factories) {
        final SaslClient saslClient = factory.createSaslClient(new String[]{mechanism}, authorizationId, protocol,
            serverName, props, cbh);
        if (saslClient != null) {
          return saslClient;
        }
      }
    }
  }
  return null;
}
 
Example 5
Source Project: cxf   Source File: SAMLUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static SamlAssertionWrapper createAssertion(CallbackHandler handler,
                                               SelfSignInfo info) throws Fault {

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(handler, samlCallback);

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        assertion.signAssertion(info.getUser(),
                                info.getPassword(),
                                info.getCrypto(),
                                false);
        return assertion;
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 6
Source Project: cxf   Source File: SAMLDelegationTest.java    License: Apache License 2.0 6 votes vote down vote up
private Element createSAMLAssertion(
    String tokenType, String keyType, Crypto crypto, String signatureUsername,
    CallbackHandler callbackHandler, String user, String issuer
) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();

    TokenProviderParameters providerParameters =
        createProviderParameters(
            tokenType, keyType, crypto, signatureUsername, callbackHandler, user, issuer
        );

    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    return (Element)providerResponse.getToken();
}
 
Example 7
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 8
Source Project: cxf-fediz   Source File: FederationProcessorImpl.java    License: Apache License 2.0 6 votes vote down vote up
private String resolveAuthenticationType(HttpServletRequest request, FedizContext config) throws IOException,
    UnsupportedCallbackException {
    Object wAuthObj = ((FederationProtocol)config.getProtocol()).getAuthenticationType();
    String wAuth = null;
    if (wAuthObj != null) {
        if (wAuthObj instanceof String) {
            wAuth = (String)wAuthObj;
        } else if (wAuthObj instanceof CallbackHandler) {
            CallbackHandler wauthCB = (CallbackHandler)wAuthObj;
            WAuthCallback callback = new WAuthCallback(request);
            wauthCB.handle(new Callback[] {
                callback
            });
            wAuth = callback.getWauth();
        }
    }
    return wAuth;
}
 
Example 9
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected Element getDelegationSecurityToken(Object delegationObject) throws Exception {
    if (delegationObject != null) {
        final boolean isString = delegationObject instanceof String;
        final boolean isElement = delegationObject instanceof Element; 
        final boolean isCallbackHandler = delegationObject instanceof CallbackHandler;
        if (isString || isElement || isCallbackHandler) {
            if (isString) {
                final Document doc =
                    DOMUtils.readXml(new StringReader((String) delegationObject));
                return doc.getDocumentElement();
            } else if (isElement) {
                return (Element) delegationObject;
            } else {
                DelegationCallback callback = new DelegationCallback(message);
                ((CallbackHandler)delegationObject).handle(new Callback[]{callback});
                return callback.getToken();
            }
        }
    }
    return null;
}
 
Example 10
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected Element getDelegationSecurityToken(Object delegationObject) throws Exception {
    if (delegationObject != null) {
        final boolean isString = delegationObject instanceof String;
        final boolean isElement = delegationObject instanceof Element; 
        final boolean isCallbackHandler = delegationObject instanceof CallbackHandler;
        if (isString || isElement || isCallbackHandler) {
            if (isString) {
                final Document doc =
                    DOMUtils.readXml(new StringReader((String) delegationObject));
                return doc.getDocumentElement();
            } else if (isElement) {
                return (Element) delegationObject;
            } else {
                DelegationCallback callback = new DelegationCallback(message);
                ((CallbackHandler)delegationObject).handle(new Callback[]{callback});
                return callback.getToken();
            }
        }
    }
    return null;
}
 
Example 11
Source Project: cxf   Source File: SAMLProtocolResponseValidator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate the Response signature (if it exists)
 */
private void validateResponseSignature(
    org.opensaml.saml.saml1.core.Response samlResponse,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    if (!samlResponse.isSigned()) {
        return;
    }

    // Required to make IdResolver happy in OpenSAML
    Attr idAttr = samlResponse.getDOM().getAttributeNodeNS(null, "ID");
    if (idAttr != null) {
        samlResponse.getDOM().setIdAttributeNode(idAttr, true);
    }

    validateResponseSignature(
        samlResponse.getSignature(), samlResponse.getDOM().getOwnerDocument(),
        sigCrypto, callbackHandler
    );
}
 
Example 12
Source Project: jdk8u-jdk   Source File: FactoryImpl.java    License: GNU General Public License v2.0 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 13
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 14
Source Project: lams   Source File: JaasSecurityManagerBase.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Creates a JaasSecurityManager for with a securityDomain
 name of that given by the 'securityDomain' argument.
 @param securityDomain the name of the security domain
 @param handler the JAAS callback handler instance to use
 @exception UndeclaredThrowableException thrown if handler does not
   implement a setSecurityInfo(Princpal, Object) method
 */
public JaasSecurityManagerBase(String securityDomain, CallbackHandler handler)
{
   this.securityDomain = SecurityUtil.unprefixSecurityDomain( securityDomain );
   this.handler = handler;
   String categoryName = getClass().getName()+'.'+securityDomain;

   // Get the setSecurityInfo(Principal principal, Object credential) method
   Class<?>[] sig = {Principal.class, Object.class};
   try
   {
      setSecurityInfo = handler.getClass().getMethod("setSecurityInfo", sig);
   }
   catch (Exception e)
   {
      throw new UndeclaredThrowableException(e, PicketBoxMessages.MESSAGES.unableToFindSetSecurityInfoMessage());
   } 
}
 
Example 15
@Override
protected final KeyStore.ProtectionParameter getKeyProtection(
        final String entryAlias,
        final X509Certificate entryCert,
        final KeyEntryPasswordProvider entryPasswordProvider)
{
    if (null == entryPasswordProvider)
    {
        return null;
    }

    return new KeyStore.CallbackHandlerProtection(new CallbackHandler()
    {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
        {
            PasswordCallback c = (PasswordCallback) callbacks[0];
            c.setPassword(entryPasswordProvider.getPassword(entryAlias, entryCert));
        }
    });
}
 
Example 16
Source Project: cxf   Source File: SAMLTokenValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
private Element createSAMLAssertionWithClaimsProvider(
    String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler
) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    AttributeStatementProvider statementProvider = new ClaimsAttributeStatementProvider();
    samlTokenProvider.setAttributeStatementProviders(Collections.singletonList(statementProvider));
    TokenProviderParameters providerParameters =
        createProviderParameters(
            "alice", tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler
        );
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    return (Element)providerResponse.getToken();
}
 
Example 17
Source Project: openjdk-8   Source File: FactoryImpl.java    License: GNU General Public License v2.0 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 18
Source Project: activemq-artemis   Source File: LDAPLoginModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNullPassword() throws Exception {
   LoginContext context = new LoginContext("LDAPLogin", new CallbackHandler() {
      @Override
      public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
         for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
               ((NameCallback) callbacks[i]).setName("first");
            } else if (callbacks[i] instanceof PasswordCallback) {
               ((PasswordCallback) callbacks[i]).setPassword(null);
            } else {
               throw new UnsupportedCallbackException(callbacks[i]);
            }
         }
      }
   });
   try {
      context.login();
      fail("Should have thrown a FailedLoginException");
   } catch (FailedLoginException fle) {
      assertEquals("Password cannot be null or empty", fle.getMessage());
   }
   context.logout();
}
 
Example 19
Source Project: cxf   Source File: WSS4JUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static PasswordEncryptor getPasswordEncryptor(Message message) {
    if (message == null) {
        return null;
    }
    PasswordEncryptor passwordEncryptor =
        (PasswordEncryptor)message.getContextualProperty(
            SecurityConstants.PASSWORD_ENCRYPTOR_INSTANCE
        );
    if (passwordEncryptor != null) {
        return passwordEncryptor;
    }

    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        CallbackHandler callbackHandler = SecurityUtils.getCallbackHandler(o);
        if (callbackHandler != null) {
            return new JasyptPasswordEncryptor(callbackHandler);
        }
    } catch (Exception ex) {
        return null;
    }

    return null;
}
 
Example 20
Source Project: steady   Source File: UsernameTokenInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public String getPassword(String userName, UsernameToken info, int type, SoapMessage message) {
    //Then try to get the password from the given callback handler

    CallbackHandler handler = getCallback(message);
    if (handler == null) {
        policyNotAsserted(info, "No callback handler and no password available", message);
        return null;
    }
    
    WSPasswordCallback[] cb = {new WSPasswordCallback(userName,
                                                      type)};
    try {
        handler.handle(cb);
    } catch (Exception e) {
        policyNotAsserted(info, e, message);
    }
    
    //get the password
    return cb[0].getPassword();
}
 
Example 21
Source Project: openjdk-8   Source File: P11KeyStore.java    License: GNU General Public License v2.0 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 22
Source Project: openjdk-jdk9   Source File: FactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a new instance of the NTLM SASL server mechanism.
 * Argument checks are performed in SaslServer's constructor.
 * @return 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 23
protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}
 
Example 24
Source Project: cxf   Source File: IssueUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(token.getToken().getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(token.getToken(), requestData);
}
 
Example 25
Source Project: lams   Source File: JBossClientAuthConfig.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new JBossClientAuthConfig.
 * 
 * @param layer Message Layer
 * @param appContext Application Context
 * @param handler Callback Handler to be passed to auth modules
 * @param properties Contextual properties
 */ 
@SuppressWarnings("rawtypes")
public JBossClientAuthConfig(String layer, String appContext,
      CallbackHandler handler, Map properties)
{
   this.layer = layer;
   this.contextId = appContext;
   this.callbackHandler = handler;
   this.contextProperties = properties;
}
 
Example 26
Source Project: steady   Source File: SpnegoContextTokenInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private SpnegoTokenContext handleBinaryExchange(
    Element binaryExchange,
    Message message,
    String namespace
) throws Exception {
    if (binaryExchange == null) {
        throw new Exception("No BinaryExchange element received");
    }
    String encoding = binaryExchange.getAttributeNS(null, "EncodingType");
    if (!BinarySecurity.BASE64_ENCODING.equals(encoding)) {
        throw new Exception("Unknown encoding type: " + encoding);
    }

    String valueType = binaryExchange.getAttributeNS(null, "ValueType");
    if (!(namespace + "/spnego").equals(valueType)) {
        throw new Exception("Unknown value type: " + valueType);
    }

    String content = DOMUtils.getContent(binaryExchange);
    byte[] decodedContent = Base64.decode(content);
    
    String jaasContext = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME);
    String kerberosSpn = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_SPN);
    CallbackHandler callbackHandler = 
        NegotiationUtils.getCallbackHandler(
            message.getContextualProperty(SecurityConstants.CALLBACK_HANDLER), this.getClass()
        );

    SpnegoTokenContext spnegoToken = new SpnegoTokenContext();
    spnegoToken.validateServiceTicket(
        jaasContext, callbackHandler, kerberosSpn, decodedContent
    );
    return spnegoToken;
}
 
Example 27
Source Project: jdk8u_jdk   Source File: DisabledMechanisms.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String authorizationId = "username";
        String protocol = "ldap";
        String serverName = "server1";
        Map props = Collections.emptyMap();

        String disabled = System.getProperty("disabledMechanisms");
        if (disabled != null) {
            Security.setProperty("jdk.sasl.disabledMechanisms", disabled);
        }

        CallbackHandler callbackHandler = callbacks -> {
            for (Callback cb : callbacks) {
                if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("password".toCharArray());
                }
            }
        };

        SaslClient client = Sasl.createSaslClient(
                new String[]{"DIGEST-MD5", "NTLM"}, authorizationId,
                protocol, serverName, props, callbackHandler);
        Asserts.assertEQ(client == null ? null : client.getMechanismName(),
                args[0].equals("null") ? null : args[0]);

        SaslServer server = Sasl.createSaslServer(
                "DIGEST-MD5", protocol, serverName, props, callbackHandler);
        Asserts.assertEQ(server == null ? null : server.getMechanismName(),
                args[1].equals("null") ? null : args[1]);
    }
 
Example 28
private void testCallbackHandlerCreation(String callbackHandlerImplClassName,
        Class<?> callbackHandlerImplClass)
        throws NoSuchMethodException, SecurityException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    TestAuthenticator authenticator = new TestAuthenticator();
    authenticator.setJaspicCallbackHandlerClass(callbackHandlerImplClassName);
    Method createCallbackHandlerMethod =
            AuthenticatorBase.class.getDeclaredMethod("createCallbackHandler");
    createCallbackHandlerMethod.setAccessible(true);
    CallbackHandler callbackHandler =
            (CallbackHandler) createCallbackHandlerMethod.invoke(authenticator);
    Assert.assertTrue(callbackHandlerImplClass.isInstance(callbackHandler));
}
 
Example 29
public static Subject loginUsingPassword(final String principal, final String password) throws LoginException {
    final Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));

    final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    final Configuration conf = usePassword(principal);
    final String confName = "PasswordConf";
    final CallbackHandler callback = new KrbCallbackHandler(principal, password);
    final LoginContext loginContext = new LoginContext(confName, subject, callback, conf);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example 30
Source Project: lams   Source File: XMessageBuilder.java    License: GNU General Public License v2.0 5 votes vote down vote up
public XMessage buildExternalAuthStart(String database) {
    CallbackHandler callbackHandler = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
            for (Callback c : callbacks) {
                if (NameCallback.class.isAssignableFrom(c.getClass())) {
                    // TODO ((NameCallback) c).setName(user);
                    throw new UnsupportedCallbackException(c);
                } else if (PasswordCallback.class.isAssignableFrom(c.getClass())) {
                    // TODO ((PasswordCallback) c).setPassword(password.toCharArray());
                    throw new UnsupportedCallbackException(c);
                } else {
                    throw new UnsupportedCallbackException(c);
                }
            }
        }
    };
    try {
        // now we create the client object we use which can handle EXTERNAL mechanism for "X Protocol" to "serverName"
        String[] mechanisms = new String[] { "EXTERNAL" };
        String authorizationId = database == null || database.trim().length() == 0 ? null : database; // as per protocol spec
        String protocol = "X Protocol";
        Map<String, ?> props = null;
        // TODO: >> serverName. Is this of any use in our X Protocol exchange? Should be defined to be blank or something.
        String serverName = "<unknown>";
        SaslClient saslClient = Sasl.createSaslClient(mechanisms, authorizationId, protocol, serverName, props, callbackHandler);

        // now just pass the details to the X Protocol auth start message
        AuthenticateStart.Builder authStartBuilder = AuthenticateStart.newBuilder();
        authStartBuilder.setMechName("EXTERNAL");
        // saslClient will build the SASL response message
        authStartBuilder.setAuthData(ByteString.copyFrom(saslClient.evaluateChallenge(null)));

        return new XMessage(authStartBuilder.build());
    } catch (SaslException ex) {
        // TODO: better exception, should introduce a new exception class for auth?
        throw new RuntimeException(ex);
    }
}