use of org.ietf.jgss.GSSName in project OpenAM by OpenRock.
the class WindowsDesktopSSO method authenticateToken.
private void authenticateToken(final byte[] kerberosToken, final Set<String> trustedRealms) throws AuthLoginException, GSSException, Exception {
debug.message("In authenticationToken ...");
Subject.doAs(serviceSubject, new PrivilegedExceptionAction() {
public Object run() throws Exception {
GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null);
if (debug.messageEnabled()) {
debug.message("Context created.");
}
byte[] outToken = context.acceptSecContext(kerberosToken, 0, kerberosToken.length);
if (outToken != null) {
if (debug.messageEnabled()) {
debug.message("Token returned from acceptSecContext: \n" + DerValue.printByteArray(outToken, 0, outToken.length));
}
}
if (!context.isEstablished()) {
debug.error("Cannot establish context !");
throw new AuthLoginException(amAuthWindowsDesktopSSO, "context", null);
} else {
if (debug.messageEnabled()) {
debug.message("Context established !");
}
GSSName user = context.getSrcName();
final String userPrincipalName = user.toString();
// expected default behaviour.
if (!trustedRealms.isEmpty()) {
boolean foundTrustedRealm = false;
for (final String trustedRealm : trustedRealms) {
if (isTokenTrusted(userPrincipalName, trustedRealm)) {
foundTrustedRealm = true;
break;
}
}
if (!foundTrustedRealm) {
debug.error("Kerberos token for " + userPrincipalName + " not trusted");
final String[] data = { userPrincipalName };
throw new AuthLoginException(amAuthWindowsDesktopSSO, "untrustedToken", data);
}
}
// perform the search.
if (lookupUserInRealm) {
String org = getRequestOrg();
String userValue = getUserName(userPrincipalName);
String userName = searchUserAccount(userValue, org);
if (userName != null && !userName.isEmpty()) {
storeUsernamePasswd(userValue, null);
} else {
String[] data = { userValue, org };
debug.error("WindowsDesktopSSO.authenticateToken: " + ": Unable to find the user " + userValue);
throw new AuthLoginException(amAuthWindowsDesktopSSO, "notfound", data);
}
}
if (debug.messageEnabled()) {
debug.message("WindowsDesktopSSO.authenticateToken:" + "User authenticated: " + user.toString());
}
if (user != null) {
setPrincipal(userPrincipalName);
}
}
context.dispose();
return null;
}
});
}
use of org.ietf.jgss.GSSName in project calcite-avatica by apache.
the class HttpServerSpnegoWithoutJaasTest method testAuthenticatedClientsAllowed.
@Test
public void testAuthenticatedClientsAllowed() throws Exception {
// Create the subject for the client
final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
// Make sure the subject has a principal
assertFalse(clientPrincipals.isEmpty());
// Get a TGT for the subject (might have many, different encryption types). The first should
// be the default encryption type.
Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
assertFalse(privateCredentials.isEmpty());
KerberosTicket tgt = privateCredentials.iterator().next();
assertNotNull(tgt);
LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
// The name of the principal
final String principalName = clientPrincipals.iterator().next().getName();
// Run this code, logged in as the subject (the client)
byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws Exception {
// Logs in with Kerberos via GSS
GSSManager gssManager = GSSManager.getInstance();
Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
// Passes the GSSCredential into the HTTP client implementation
final AvaticaCommonsHttpClientSpnegoImpl httpClient = new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
return httpClient.send(new byte[0]);
}
});
// We should get a response which is "OK" with our client's name
assertNotNull(response);
assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL, new String(response, StandardCharsets.UTF_8));
}
use of org.ietf.jgss.GSSName in project calcite-avatica by apache.
the class HttpServerSpnegoWithJaasTest method testAuthenticatedClientsAllowed.
@Test
public void testAuthenticatedClientsAllowed() throws Exception {
Assume.assumeThat("Test disabled on Windows", File.separatorChar, is('/'));
// Create the subject for the client
final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
// Make sure the subject has a principal
assertFalse(clientPrincipals.isEmpty());
// Get a TGT for the subject (might have many, different encryption types). The first should
// be the default encryption type.
Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
assertFalse(privateCredentials.isEmpty());
KerberosTicket tgt = privateCredentials.iterator().next();
assertNotNull(tgt);
LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
// The name of the principal
final String principalName = clientPrincipals.iterator().next().getName();
// Run this code, logged in as the subject (the client)
byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws Exception {
// Logs in with Kerberos via GSS
GSSManager gssManager = GSSManager.getInstance();
Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
// Passes the GSSCredential into the HTTP client implementation
final AvaticaCommonsHttpClientSpnegoImpl httpClient = new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
return httpClient.send(new byte[0]);
}
});
// We should get a response which is "OK" with our client's name
assertNotNull(response);
assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL, new String(response, StandardCharsets.UTF_8));
}
use of org.ietf.jgss.GSSName in project wildfly by wildfly.
the class JBossNegotiateScheme method authenticate.
/**
* Produces Negotiate authorization Header based on token created by processChallenge.
*
* @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
* from JAAS will be used instead.
* @param request The request being authenticated
*
* @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
*
* @return an Negotiate authorization Header
*/
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (state == State.TOKEN_GENERATED) {
// hack for auto redirects
return new BasicHeader("X-dummy", "Token already generated");
}
if (state != State.CHALLENGE_RECEIVED) {
throw new IllegalStateException("Negotiation authentication process has not been initiated");
}
try {
String key = null;
if (isProxy()) {
key = ExecutionContext.HTTP_PROXY_HOST;
} else {
key = HttpCoreContext.HTTP_TARGET_HOST;
}
HttpHost host = (HttpHost) context.getAttribute(key);
if (host == null) {
throw new AuthenticationException("Authentication host is not set " + "in the execution context");
}
String authServer;
if (!this.stripPort && host.getPort() > 0) {
authServer = host.toHostString();
} else {
authServer = host.getHostName();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("init " + authServer);
}
final Oid negotiationOid = new Oid(SPNEGO_OID);
final GSSManager manager = GSSManager.getInstance();
final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
gssContext.requestCredDeleg(true);
if (token == null) {
token = new byte[0];
}
token = gssContext.initSecContext(token, 0, token.length);
if (token == null) {
state = State.FAILED;
throw new AuthenticationException("GSS security context initialization failed");
}
state = State.TOKEN_GENERATED;
String tokenstr = new String(base64codec.encode(token));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
}
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Negotiate ");
buffer.append(tokenstr);
return new BufferedHeader(buffer);
} catch (GSSException gsse) {
state = State.FAILED;
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.NO_CRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
throw new AuthenticationException(gsse.getMessage(), gsse);
// other error
throw new AuthenticationException(gsse.getMessage());
}
}
use of org.ietf.jgss.GSSName in project undertow by undertow-io.
the class SpnegoAuthenticationTestCase method testSpnegoSuccess.
@Test
public void testSpnegoSuccess() throws Exception {
final TestHttpClient client = new TestHttpClient();
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
HttpResponse result = client.execute(get);
assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
String header = getAuthHeader(NEGOTIATE, values);
assertEquals(NEGOTIATE.toString(), header);
HttpClientUtils.readResponse(result);
Subject clientSubject = login("jduke", "theduke".toCharArray());
Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
GSSManager gssManager = GSSManager.getInstance();
GSSName serverName = gssManager.createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null);
GSSContext context = gssManager.createContext(serverName, SPNEGO, null, GSSContext.DEFAULT_LIFETIME);
byte[] token = new byte[0];
boolean gotOur200 = false;
while (!context.isEstablished()) {
token = context.initSecContext(token, 0, token.length);
if (token != null && token.length > 0) {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
get.addHeader(AUTHORIZATION.toString(), NEGOTIATE + " " + FlexBase64.encodeString(token, false));
HttpResponse result = client.execute(get);
Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString());
if (headers.length > 0) {
String header = getAuthHeader(NEGOTIATE, headers);
byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
// FlexBase64.decode() returns byte buffer, which can contain backend array of greater size.
// when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes
// at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[].
token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes, NEGOTIATE.toString().length() + 1, headerBytes.length));
}
if (result.getStatusLine().getStatusCode() == StatusCodes.OK) {
Header[] values = result.getHeaders("ProcessedBy");
assertEquals(1, values.length);
assertEquals("ResponseHandler", values[0].getValue());
HttpClientUtils.readResponse(result);
assertSingleNotificationType(EventType.AUTHENTICATED);
gotOur200 = true;
} else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) {
assertTrue("We did get a header.", headers.length > 0);
HttpClientUtils.readResponse(result);
} else {
fail(String.format("Unexpected status code %d", result.getStatusLine().getStatusCode()));
}
}
}
assertTrue(gotOur200);
assertTrue(context.isEstablished());
return null;
}
});
}
Aggregations