javax.security.auth.callback.CallbackHandler Java Examples

The following examples show how to use javax.security.auth.callback.CallbackHandler. 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 check out the related API usage on the sidebar.
Example #1
Source File: AbstractSTSClient.java    From steady with 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 #2
Source File: WSS4JUtils.java    From cxf with 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 #3
Source File: FactoryImpl.java    From jdk8u60 with 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 File: LDAPLoginModuleTest.java    From activemq-artemis with 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 #5
Source File: UsernameTokenInterceptor.java    From steady with 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 #6
Source File: FactoryImpl.java    From openjdk-jdk8u with 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 #7
Source File: FactoryImpl.java    From openjdk-8 with 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 #8
Source File: P11KeyStore.java    From openjdk-8 with 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 #9
Source File: FactoryImpl.java    From openjdk-jdk9 with 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 #10
Source File: AtlasAuthenticationKerberosFilterTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: AuthenticatorBase.java    From Tomcat8-Source-Read with 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 #12
Source File: SAMLTokenValidatorTest.java    From cxf with 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 #13
Source File: SAMLUtils.java    From cxf with 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 #14
Source File: SAMLDelegationTest.java    From cxf with 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 #15
Source File: PKCS11KeyStoreKeyingDataProvider.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 File: JaasSecurityManagerBase.java    From lams with 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 #17
Source File: DynamicConfigurationTest.java    From hottub with GNU General Public License v2.0 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 #18
Source File: LoginModuleOptions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #19
Source File: FactoryImpl.java    From jdk8u-jdk with 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 #20
Source File: FederationProcessorImpl.java    From cxf-fediz with 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 #21
Source File: SAMLProtocolResponseValidator.java    From cxf with 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 #22
Source File: AbstractSTSClient.java    From steady with 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 #23
Source File: FastSaslClientFactory.java    From Bats with 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 #24
Source File: SpnegoContextTokenInInterceptor.java    From steady with 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 #25
Source File: IssueUnitTest.java    From cxf with 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 #26
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
protected CallbackHandler getCallback(RequestData reqData, int doAction, boolean utWithCallbacks) 
    throws WSSecurityException {
    if (!utWithCallbacks 
        && ((doAction & WSConstants.UT) != 0 || (doAction & WSConstants.UT_NOPASSWORD) != 0)) {
        CallbackHandler pwdCallback = null;
        try {
            pwdCallback = getCallback(reqData, doAction);
        } catch (Exception ex) {
            // ignore
        }
        return new DelegatingCallbackHandler(pwdCallback);
    } else {
        return getCallback(reqData, doAction);
    }
}
 
Example #27
Source File: HttpRequestBasedCallbackHandlerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testCallbackThrowsHandlingUnsupportedCallback() throws IOException {
  CallbackHandler handler = new HttpRequestBasedCallbackHandler(new MultiMap<String>());

  try {
    handler.handle(new Callback[] {new Callback() {}});
    fail("Should have thrown due to unsupported callback");
  } catch (UnsupportedCallbackException e) {
    // Pass.
  }
}
 
Example #28
Source File: SharedState.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
                    Map<String,?> sharedState, Map<String,?> options) {
    // check shared object
    Object shared = sharedState.get(NAME);
    if (!VALUE.equals(shared)) {
        throw new RuntimeException("Unexpected shared object: "
                + shared);
    }
}
 
Example #29
Source File: CleanState.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void go() throws Exception {
    Krb5LoginModule krb5 = new Krb5LoginModule();

    final String name = OneKDC.USER;
    final char[] password = OneKDC.PASS;
    char[] badpassword = "hellokitty".toCharArray();

    Map<String,String> map = new HashMap<>();
    map.put("useTicketCache", "false");
    map.put("doNotPrompt", "false");
    map.put("tryFirstPass", "true");
    Map<String,Object> shared = new HashMap<>();
    shared.put("javax.security.auth.login.name", name);
    shared.put("javax.security.auth.login.password", badpassword);

    krb5.initialize(new Subject(), new CallbackHandler() {
        @Override
        public void handle(Callback[] callbacks) {
            for(Callback callback: callbacks) {
                if (callback instanceof NameCallback) {
                    ((NameCallback)callback).setName(name);
                }
                if (callback instanceof PasswordCallback) {
                    ((PasswordCallback)callback).setPassword(password);
                }
            }
        }
    }, shared, map);
    krb5.login();
}
 
Example #30
Source File: SAMLTokenRenewerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element createSAMLAssertion(
        String tokenType, Crypto crypto, String signatureUsername,
        CallbackHandler callbackHandler, long ttlMs, boolean allowRenewing,
        boolean allowRenewingAfterExpiry
) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setAcceptClientLifetime(true);
    samlTokenProvider.setConditionsProvider(conditionsProvider);
    TokenProviderParameters providerParameters =
        createProviderParameters(
                tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler
        );

    Renewing renewing = new Renewing();
    renewing.setAllowRenewing(allowRenewing);
    renewing.setAllowRenewingAfterExpiry(allowRenewingAfterExpiry);
    providerParameters.getTokenRequirements().setRenewing(renewing);

    if (ttlMs != 0) {
        Lifetime lifetime = new Lifetime();

        Instant creationTime = Instant.now();
        Instant expirationTime = creationTime.plusNanos(ttlMs * 1000000L);

        lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
        lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

        providerParameters.getTokenRequirements().setLifetime(lifetime);
    }

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

    return (Element)providerResponse.getToken();
}