use of javax.security.auth.callback.CallbackHandler in project jdk8u_jdk by JetBrains.
the class RefreshKrb5Config method main.
public static void main(String[] args) throws LoginException, IOException {
Map<String, String> principals = new HashMap<>();
principals.put(USER_PRINCIPAL, USER_PASSWORD);
principals.put(KRBTGT_PRINCIPAL, null);
System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);
// start a local KDC, and save krb5 config
KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
KDC.saveConfig(KRB5_CONF_FILENAME, kdc, "max_retries = 1");
System.setProperty("java.security.auth.login.config", TEST_SRC + File.separator + "refreshKrb5Config.jaas");
CallbackHandler handler = new Helper.UserPasswordHandler(USER, USER_PASSWORD);
// set incorrect KDC
System.out.println("java.security.krb5.kdc = " + NOT_EXISTING_HOST);
System.setProperty("java.security.krb5.kdc", NOT_EXISTING_HOST);
System.out.println("java.security.krb5.realm = " + REALM);
System.setProperty("java.security.krb5.realm", REALM);
try {
new LoginContext("Refreshable", handler).login();
throw new RuntimeException("Expected exception not thrown");
} catch (LoginException le) {
System.out.println("Expected login failure: " + le);
}
// reset properties
System.out.println("Reset java.security.krb5.kdc");
System.clearProperty("java.security.krb5.kdc");
System.out.println("Reset java.security.krb5.realm");
System.clearProperty("java.security.krb5.realm");
// login with not-refreshable config
try {
new LoginContext("NotRefreshable", handler).login();
throw new RuntimeException("Expected exception not thrown");
} catch (LoginException le) {
System.out.println("Expected login failure: " + le);
}
// login with refreshable config
new LoginContext("Refreshable", handler).login();
System.out.println("Test passed");
}
use of javax.security.auth.callback.CallbackHandler in project tomee by apache.
the class OpenEJBJaasPasswordAuthenticator method authenticate.
@Override
public boolean authenticate(final String username, final String password, final ServerSession session) {
try {
final Subject subject = new Subject();
final LoginContext loginContext = new LoginContext(getDomain(), subject, new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (final Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callback);
}
}
}
});
loginContext.login();
session.setAttribute(USERNAME_KEY, username);
session.setAttribute(LOGIN_CONTEXT_KEY, loginContext);
return true;
} catch (Exception e) {
LOGGER.debug("can't log using username '" + username + "'", e);
return false;
}
}
use of javax.security.auth.callback.CallbackHandler in project cxf by apache.
the class JAASLoginInterceptor method handleMessage.
public void handleMessage(final Message message) throws Fault {
if (allowNamedPrincipals) {
SecurityContext sc = message.get(SecurityContext.class);
if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) {
return;
}
}
CallbackHandler handler = getFirstCallbackHandler(message);
if (handler == null && !allowAnonymous) {
throw new AuthenticationException("Authentication required but no authentication information was supplied");
}
try {
LoginContext ctx = new LoginContext(getContextName(), null, handler, loginConfig);
ctx.login();
Subject subject = ctx.getSubject();
String name = getUsername(handler);
message.put(SecurityContext.class, createSecurityContext(name, subject));
// This allows other code to retrieve the subject using pure JAAS
if (useDoAs) {
Subject.doAs(subject, new PrivilegedAction<Void>() {
@Override
public Void run() {
InterceptorChain chain = message.getInterceptorChain();
if (chain != null) {
chain.doIntercept(message);
}
return null;
}
});
}
} catch (LoginException ex) {
String errorMessage = "Authentication failed: " + ex.getMessage();
LOG.log(Level.FINE, errorMessage, ex);
if (reportFault) {
AuthenticationException aex = new AuthenticationException(errorMessage);
aex.initCause(ex);
throw aex;
}
throw new AuthenticationException("Authentication failed (details can be found in server log)");
}
}
use of javax.security.auth.callback.CallbackHandler in project cxf by apache.
the class SamlRedirectBindingFilter method signRequest.
/**
* Sign a request according to the redirect binding spec for Web SSO
*/
private void signRequest(String authnRequest, String relayState, UriBuilder ub) throws Exception {
Crypto crypto = getSignatureCrypto();
if (crypto == null) {
LOG.fine("No crypto instance of properties file configured for signature");
throw ExceptionUtils.toInternalServerErrorException(null, null);
}
String signatureUser = getSignatureUsername();
if (signatureUser == null) {
LOG.fine("No user configured for signature");
throw ExceptionUtils.toInternalServerErrorException(null, null);
}
CallbackHandler callbackHandler = getCallbackHandler();
if (callbackHandler == null) {
LOG.fine("No CallbackHandler configured to supply a password for signature");
throw ExceptionUtils.toInternalServerErrorException(null, null);
}
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(signatureUser);
X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
if (issuerCerts == null) {
throw new Exception("No issuer certs were found to sign the request using name: " + signatureUser);
}
String sigAlgo = SSOConstants.RSA_SHA1;
String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
String jceSigAlgo = "SHA1withRSA";
LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
sigAlgo = SSOConstants.DSA_SHA1;
jceSigAlgo = "SHA1withDSA";
}
LOG.fine("Using Signature algorithm " + sigAlgo);
ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()));
// Get the password
WSPasswordCallback[] cb = { new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE) };
callbackHandler.handle(cb);
String password = cb[0].getPassword();
// Get the private key
PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password);
// Sign the request
Signature signature = Signature.getInstance(jceSigAlgo);
signature.initSign(privateKey);
String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name());
signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
byte[] signBytes = signature.sign();
String encodedSignature = Base64.getEncoder().encodeToString(signBytes);
ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name()));
}
use of javax.security.auth.callback.CallbackHandler in project cxf by apache.
the class AbstractSAMLTokenProvider method signToken.
protected void signToken(SamlAssertionWrapper assertion, RealmProperties samlRealm, STSPropertiesMBean stsProperties, KeyRequirements keyRequirements) throws Exception {
// Initialise signature objects with defaults of STSPropertiesMBean
Crypto signatureCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
SignatureProperties signatureProperties = stsProperties.getSignatureProperties();
String alias = stsProperties.getSignatureUsername();
if (samlRealm != null) {
// callbackhandler and alias of STSPropertiesMBean is ignored
if (samlRealm.getSignatureCrypto() != null) {
LOG.fine("SAMLRealm signature keystore used");
signatureCrypto = samlRealm.getSignatureCrypto();
callbackHandler = samlRealm.getCallbackHandler();
alias = samlRealm.getSignatureAlias();
}
// SignatureProperties can be defined independently of SignatureCrypto
if (samlRealm.getSignatureProperties() != null) {
signatureProperties = samlRealm.getSignatureProperties();
}
}
// Get the signature algorithm to use
String signatureAlgorithm = keyRequirements.getSignatureAlgorithm();
if (signatureAlgorithm == null) {
// If none then default to what is configured
signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
} else {
List<String> supportedAlgorithms = signatureProperties.getAcceptedSignatureAlgorithms();
if (!supportedAlgorithms.contains(signatureAlgorithm)) {
signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("SignatureAlgorithm not supported, defaulting to: " + signatureAlgorithm);
}
}
}
// Get the c14n algorithm to use
String c14nAlgorithm = keyRequirements.getC14nAlgorithm();
if (c14nAlgorithm == null) {
// If none then default to what is configured
c14nAlgorithm = signatureProperties.getC14nAlgorithm();
} else {
List<String> supportedAlgorithms = signatureProperties.getAcceptedC14nAlgorithms();
if (!supportedAlgorithms.contains(c14nAlgorithm)) {
c14nAlgorithm = signatureProperties.getC14nAlgorithm();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("C14nAlgorithm not supported, defaulting to: " + c14nAlgorithm);
}
}
}
// If alias not defined, get the default of the SignatureCrypto
if ((alias == null || "".equals(alias)) && (signatureCrypto != null)) {
alias = signatureCrypto.getDefaultX509Identifier();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Signature alias is null so using default alias: " + alias);
}
}
// Get the password
String password = null;
if (callbackHandler != null) {
WSPasswordCallback[] cb = { new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE) };
LOG.fine("Creating SAML Token");
callbackHandler.handle(cb);
password = cb[0].getPassword();
}
LOG.fine("Signing SAML Token");
boolean useKeyValue = signatureProperties.isUseKeyValue();
assertion.signAssertion(alias, password, signatureCrypto, useKeyValue, c14nAlgorithm, signatureAlgorithm, signatureProperties.getDigestAlgorithm());
}
Aggregations