How to synchronize Servlet client transaction? - restcomm

Hello I am currently using restcomm-sip-servlets-4.0.75-apache-tomcat-8.0.26. and I am having issues canceling an ongoing request from the http request thread. I noticed that this issue only appears to happen when I create a new request with an auth header like so :
AuthInfo authInfo = sipFactory.createAuthInfo();
authInfo.addAuthInfo(
response.getStatus(),
realm,myauth,password);
SipServletRequest challengeRequest = response.getSession().createRequest(
response.getRequest().getMethod());
(String)session.getAttribute("FirstPartyContent");
if(session.getAttribute("FirstPartyContent") !=null){
challengeRequest.setContent(session.getAttribute("FirstPartyContent"),(String) session.getAttribute("FirstPartyContentType"));
}
challengeRequest.addAuthHeader(response, authInfo);
challengeRequest.getFrom().setDisplayName(auth.getDisplayName());
session.removeAttribute("original");
session.setAttribute("original", challengeRequest);
challengeRequest.send();
When a request comes in via the http interface I look for the SipApplicationSession like so:
SipSessionsUtil sipSessionsUtil =
(SipSessionsUtil) session.getServletContext().
getAttribute("javax.servlet.sip.SipSessionsUtil");
logger.info("found servlet contxt for sipsession util");
SipApplicationSession tobecancelledsess = sipSessionsUtil.getApplicationSessionById(sessionapplicationID);
I then create a cancel request from the session request stored like so :
SipServletRequest req = (SipServletRequest)tobecancelledsess.getAttribute("original");
drequest = req.createCancel();
although the remote server responds a provisional with to-tag I get:
2017-04-28 16:26:04,470 DEBUG [SipServletMessageImpl] (http-bio-8443-exec-1) transaction null transactionId = null transactionType false
2017-04-28 16:26:04,470 DEBUG [SipServletMessageImpl] (http-bio-8443-exec-1) transaction null transactionId = null transactionType false
java.lang.IllegalStateException: No client transaction found! null
at org.mobicents.servlet.sip.message.SipServletRequestImpl.createCancel(SipServletRequestImpl.java:258)
at org.example.servlet.sip.CallContainer.CancelSession(CallContainer.java:319)
at org.example.servlet.sip.CallContainer.CheckCancel(CallContainer.java:274)
at org.example.servlet.sip.SimpleWebServlet.doPut(SimpleWebServlet.java:360)
at org.example.servlet.sip.SimpleWebServlet.service(SimpleWebServlet.java:149)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.mobicents.servlet.sip.startup.SipStandardContextValve.invoke(SipStandardContextValve.java:262)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I noticed that when I cancel the request from the servlet class I don't have this issue.

I found that setting a context attribute at the response like this solves my issue:
if (resp.getStatus() == SipServletResponse.SC_RINGING){
SipSession session = resp.getSession();
resp.getSession().getServletContext().setAttribute("ringing",true);
}
I then grab the session context like this
SipServletRequest req = (SipServletRequest)tobecancelledsess.getAttribute("original");
Boolean ringed = (Boolean ) tobecancelledsess.getServletContext().getAttribute("ringing");
if(ringed == Boolean.True)
drequest = req.createCancel();
and eventually you need to send the cancel request with send();

Related

Ktor-server-test-host did not cleaned up Exposed database instannce across tests

I'm working on a web service using Ktor 1.6.8 and Exposed 0.39.2.
My application module and database is setup as following:
fun Application.module(testing: Boolean = false) {
val hikariConfig =
HikariConfig().apply {
driverClassName = "org.postgresql.Driver"
jdbcUrl = environment.config.propertyOrNull("ktor.database.url")?.getString()
username = environment.config.propertyOrNull("ktor.database.username")?.getString()
password = environment.config.propertyOrNull("ktor.database.password")?.getString()
maximumPoolSize = 10
isAutoCommit = false
transactionIsolation = "TRANSACTION_REPEATABLE_READ"
validate()
}
val pool = HikariDataSource(hikariConfig)
val db = Database.connect(pool, {}, DatabaseConfig { useNestedTransactions = true })
}
I use ktor-server-test-host, Test Containers and junit 5 to test the service. My test looks similar like below:
#Testcontainers
class SampleApplicationTest{
companion object {
#Container
val postgreSQLContainer = PostgreSQLContainer<Nothing>(DockerImageName.parse("postgres:13.4-alpine")).apply {
withDatabaseName("database_test")
}
}
#Test
internal fun `should make request successfully`() {
withTestApplication({
(environment.config as MapApplicationConfig).apply {
put("ktor.database.url", postgreSQLContainer.jdbcUrl)
put("ktor.database.user", postgreSQLContainer.username)
put("ktor.database.password", postgreSQLContainer.password)
}
module(testing = true)
}) {
handleRequest(...)
}
}
}
I observed an issue that if I ran multiple test classes together, some requests ended up using old Exposed db instance that was setup in a previous test class, causing the test case failed because the underlying database was already stopped.
When I ran one test class at a time, all were running fine.
Please refer to the log below for the error stack trace:
2022-10-01 08:00:36.102 [DefaultDispatcher-worker-5 #request#103] WARN Exposed - Transaction attempt #1 failed: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.. Statement(s): INSERT INTO cards (...)
org.jetbrains.exposed.exceptions.ExposedSQLException: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.
at org.jetbrains.exposed.sql.statements.Statement.executeIn$exposed_core(Statement.kt:49)
at org.jetbrains.exposed.sql.Transaction.exec(Transaction.kt:143)
at org.jetbrains.exposed.sql.Transaction.exec(Transaction.kt:128)
at org.jetbrains.exposed.sql.statements.Statement.execute(Statement.kt:28)
at org.jetbrains.exposed.sql.QueriesKt.insert(Queries.kt:73)
at com.example.application.services.CardService$createCard$row$1.invokeSuspend(CardService.kt:53)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:127)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
Caused by: java.sql.SQLTransientConnectionException: HikariPool-4 - Connection is not available, request timed out after 30001ms.
at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:695)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:197)
at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:162)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:100)
at org.jetbrains.exposed.sql.Database$Companion$connect$3.invoke(Database.kt:142)
at org.jetbrains.exposed.sql.Database$Companion$connect$3.invoke(Database.kt:139)
at org.jetbrains.exposed.sql.Database$Companion$doConnect$3.invoke(Database.kt:127)
at org.jetbrains.exposed.sql.Database$Companion$doConnect$3.invoke(Database.kt:128)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction$connectionLazy$1.invoke(ThreadLocalTransactionManager.kt:69)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction$connectionLazy$1.invoke(ThreadLocalTransactionManager.kt:68)
at kotlin.UnsafeLazyImpl.getValue(Lazy.kt:81)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManager$ThreadLocalTransaction.getConnection(ThreadLocalTransactionManager.kt:75)
at org.jetbrains.exposed.sql.Transaction.getConnection(Transaction.kt)
at org.jetbrains.exposed.sql.statements.InsertStatement.prepared(InsertStatement.kt:157)
at org.jetbrains.exposed.sql.statements.Statement.executeIn$exposed_core(Statement.kt:47)
... 19 common frames omitted
Caused by: org.postgresql.util.PSQLException: Connection to localhost:49544 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:223)
at org.postgresql.Driver.makeConnection(Driver.java:465)
at org.postgresql.Driver.connect(Driver.java:264)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
at com.zaxxer.hikari.pool.HikariPool.access$100(HikariPool.java:71)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:725)
at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:711)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.pollConnect(Native Method)
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
I tried to add some cleanup code for Exposed's TransactionManager in my application module as following:
fun Application.module(testing: Boolean = false) {
// ...
val db = Database.connect(pool, {}, DatabaseConfig { useNestedTransactions = true })
if (testing) {
environment.monitor.subscribe(ApplicationStopped) {
TransactionManager.closeAndUnregister(db)
}
}
}
However, the issue still happened, and I also observed additional error as following:
2022-10-01 08:00:36.109 [DefaultDispatcher-worker-5 #request#93] ERROR Application - Unexpected error
java.lang.RuntimeException: database org.jetbrains.exposed.sql.Database#3bf4644c don't have any transaction manager
at org.jetbrains.exposed.sql.transactions.TransactionApiKt.getTransactionManager(TransactionApi.kt:149)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.closeAsync(Suspended.kt:85)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.access$closeAsync(Suspended.kt:1)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:138)
(Coroutine boundary)
at org.mpierce.ktor.newrelic.KtorNewRelicKt$runPipelineInTransaction$2.invokeSuspend(KtorNewRelic.kt:178)
at org.mpierce.ktor.newrelic.KtorNewRelicKt$setUpNewRelic$2.invokeSuspend(KtorNewRelic.kt:104)
at io.ktor.routing.Routing.executeResult(Routing.kt:154)
at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:107)
at io.ktor.features.ContentNegotiation$Feature$install$1.invokeSuspend(ContentNegotiation.kt:145)
at io.ktor.features.StatusPages$interceptCall$2.invokeSuspend(StatusPages.kt:102)
at io.ktor.features.StatusPages.interceptCall(StatusPages.kt:101)
at io.ktor.features.StatusPages$Feature$install$2.invokeSuspend(StatusPages.kt:142)
at io.ktor.features.CallLogging$Feature$install$2.invokeSuspend(CallLogging.kt:188)
at io.ktor.server.testing.TestApplicationEngine$callInterceptor$1.invokeSuspend(TestApplicationEngine.kt:296)
at io.ktor.server.testing.TestApplicationEngine$2.invokeSuspend(TestApplicationEngine.kt:50)
Caused by: java.lang.RuntimeException: database org.jetbrains.exposed.sql.Database#3bf4644c don't have any transaction manager
at org.jetbrains.exposed.sql.transactions.TransactionApiKt.getTransactionManager(TransactionApi.kt:149)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.closeAsync(Suspended.kt:85)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt.access$closeAsync(Suspended.kt:1)
at org.jetbrains.exposed.sql.transactions.experimental.SuspendedKt$suspendedTransactionAsyncInternal$1.invokeSuspend(Suspended.kt:138)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
Could someone show me what could be the issue here with my application code & test setup?
Thanks and regards.

io.helidon.webserver.ServerResponse.send() throwing error on server but file downloaded on front end

Trying to write one sample for (file upload and download) error in server.
Though it downloads the file in the frontend, getting error in server.
For Routing--
WebServer.builder(getRouting()).port(8080).build().start();
private static Routing getRouting() throws Exception{
return Routing.builder().register("/filetest", JerseySupport.builder().register(FileController.class).build())
.build();
}
#RequestScoped
public class FileController {
#Context
ServerRequest req;
#Context
ServerResponse res;
#GET
#Path("/{fname}")
public void download(#PathParam("fname") String fname) {
try {
//Getting the file
java.nio.file.Path filepath = Paths.get("c:/"+fname+".txt");
ResponseHeaders headers = res.headers();
headers.contentType(io.helidon.common.http.MediaType.APPLICATION_OCTET_STREAM);
headers.put(Http.Header.CONTENT_DISPOSITION, ContentDisposition.builder()
.filename(filepath.getFileName().toString())
.build()
.toString());
res.send(filepath);
}catch(Exception e) {
}
}
Jul 29, 2021 6:20:36 PM
io.helidon.webserver.RequestRouting$RoutedRequest defaultHandler
WARNING: Default error handler: Unhandled exception encountered.
java.util.concurrent.ExecutionException: Unhandled 'cause' of this
exception encountered. at
io.helidon.webserver.RequestRouting$RoutedRequest.defaultHandler(RequestRouting.java:397)
at
io.helidon.webserver.RequestRouting$RoutedRequest.nextNoCheck(RequestRouting.java:377)
at
io.helidon.webserver.RequestRouting$RoutedRequest.next(RequestRouting.java:420)
at
io.helidon.webserver.jersey.ResponseWriter.failure(ResponseWriter.java:133)
at
org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:438)
at
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248) at
org.glassfish.jersey.internal.Errors$1.call(Errors.java:244) at
org.glassfish.jersey.internal.Errors.process(Errors.java:292) at
org.glassfish.jersey.internal.Errors.process(Errors.java:274) at
org.glassfish.jersey.internal.Errors.process(Errors.java:244) at
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
at
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:234)
at
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
at
io.helidon.webserver.jersey.JerseySupport$JerseyHandler.lambda$doAccept$3(JerseySupport.java:299)
at io.helidon.common.context.Contexts.runInContext(Contexts.java:117)
at
io.helidon.common.context.ContextAwareExecutorImpl.lambda$wrap$5(ContextAwareExecutorImpl.java:154)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834) Caused by:
io.helidon.common.http.AlreadyCompletedException: Response status code
and headers are already completed (sent to the client)! at
io.helidon.webserver.HashResponseHeaders$CompletionSupport.runIfNotCompleted(HashResponseHeaders.java:384)
at
io.helidon.webserver.HashResponseHeaders.httpStatus(HashResponseHeaders.java:251)
at io.helidon.webserver.Response.status(Response.java:122) at
io.helidon.webserver.Response.status(Response.java:48) at
io.helidon.webserver.jersey.ResponseWriter.writeResponseStatusAndHeaders(ResponseWriter.java:81)
at
org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:607)
at
org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:373)
at
org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:363)
at
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:258)
... 14 more
Jul 29, 2021 6:20:36 PM
io.helidon.webserver.RequestRouting$RoutedRequest defaultHandler
WARNING: Cannot perform error handling of the throwable (see cause of
this exception) because headers were already sent
java.lang.IllegalStateException: Headers already sent. Cannot handle
the cause of this exception. at
io.helidon.webserver.RequestRouting$RoutedRequest.defaultHandler(RequestRouting.java:405)
at
io.helidon.webserver.RequestRouting$RoutedRequest.nextNoCheck(RequestRouting.java:377)
at
io.helidon.webserver.RequestRouting$RoutedRequest.next(RequestRouting.java:420)
at
io.helidon.webserver.jersey.ResponseWriter.failure(ResponseWriter.java:133)
at
org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:438)
at
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248) at
org.glassfish.jersey.internal.Errors$1.call(Errors.java:244) at
org.glassfish.jersey.internal.Errors.process(Errors.java:292) at
org.glassfish.jersey.internal.Errors.process(Errors.java:274) at
org.glassfish.jersey.internal.Errors.process(Errors.java:244) at
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
at
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:234)
at
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
at
io.helidon.webserver.jersey.JerseySupport$JerseyHandler.lambda$doAccept$3(JerseySupport.java:299)
at io.helidon.common.context.Contexts.runInContext(Contexts.java:117)
at
io.helidon.common.context.ContextAwareExecutorImpl.lambda$wrap$5(ContextAwareExecutorImpl.java:154)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834) Caused by:
io.helidon.common.http.AlreadyCompletedException: Response status code
and headers are already completed (sent to the client)! at
io.helidon.webserver.HashResponseHeaders$CompletionSupport.runIfNotCompleted(HashResponseHeaders.java:384)
at
io.helidon.webserver.HashResponseHeaders.httpStatus(HashResponseHeaders.java:251)
at io.helidon.webserver.Response.status(Response.java:122) at
io.helidon.webserver.Response.status(Response.java:48) at
io.helidon.webserver.jersey.ResponseWriter.writeResponseStatusAndHeaders(ResponseWriter.java:81)
at
org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:607)
at
org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:373)
at
org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:363)
at
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:258)
... 14 more
When using Helidon MP, Jersey is responsible for sending the response.
In the code above you are using the underlying WebServer and sending a response inside the body of a JAXRS resource method, when Jersey sends the response the exception is thrown because it was already sent.
Helidon MP Multipart example
Jersey Multipart documentation

handleChallenge() being trigger even handleSuccess() in mfp authentication

Good day,
I have a mobile app that will call through mfp8 to my channel service.
In my front end angular code, I have create the mfp securityCheckChallengHadler, and call the mfp login, the following is my code of front end:
this.userLoginChallengeHandler = null;
this.userLoginChallengeHandler = WL.Client.createSecurityCheckChallengeHandler(this.securityCheckName);
this.userLoginChallengeHandler.securityCheckName = this.securityCheckName;
this.userLoginChallengeHandler.handleSuccess = (loginSuccess) => {
console.log("handleSuccess");
this.isChallenged = false;
if (this.currentEventHandler != this.eventHandler.success) {
this.currentLoginGrantType = this.processLoginGrantType;
//alert("initEventHandler|loginSuccess=\n" + JSON.stringify(loginSuccess));
this.mfpAuthResponse = {
id: loginSuccess.id,
accessToken: loginSuccess.user.attributes.access_token,
tokenType: loginSuccess.user.attributes.token_type,
expiresIn: loginSuccess.user.attributes.expires_in,
scope: loginSuccess.user.attributes.scope,
clientId: loginSuccess.user.attributes.client_id
};
}
this.currentEventHandler = this.eventHandler.success;
};
this.userLoginChallengeHandler.handleFailure = (loginError) => {
console.log("handleFailure");
this.isChallenged = false;
if (this.currentEventHandler != this.eventHandler.failure) {
this.authFailureEvent.emit(loginError);
}
this.currentEventHandler = this.eventHandler.failure;
};
this.userLoginChallengeHandler.handleChallenge = (challenge) => {
console.log("handleChallenge");
this.isChallenged = true;
this.challengeResponseModel = challenge;
this.authChallengeEvent.emit(challenge);
this.currentEventHandler = this.eventHandler.challenge;
};
And this is the part call the WLAuthorizationManager.login(this.securityCheckName, authObj):
if (this.isChallenged) {
console.log("mfp-performLogin|submitChallengeAnswer=");
this.userLoginChallengeHandler.submitChallengeAnswer(authObj);
} else {
console.log("mfp-performLogin|WLAuthorizationManager.login=");
WLAuthorizationManager.login(this.securityCheckName, authObj).then(
() => {
console.log("mfp-performLogin|WLAuthorizationManager.login.performed=" + performed + "\nmfpAuthResponse=\n" + JSON.stringify(this.mfpAuthResponse) + "\n\n");
if (!performed) {
this.ngZone.run(() => {
this.authSuccessEvent.emit(this.mfpAuthResponse);
});
}
performed = true;
},
(err) => {
console.log("mfp-performLogin|WLAuthorizationManager.login.err=\n\n" + JSON.stringify(err) + "\n");
console.log('wllogin err => ', err);
this.authFailureEvent.emit(err);
}
);
}
During WLAuthorizationManager.login(this.securityCheckName, authObj), I saw the handleSuccess() being trigger, as my understanding, this is means my authentication with mfp is successful, and I can proceed to call any protected resource. However, not only handleSuccess(), I saw handleChallenge() being trigger as well.
And because of this, I cant get the accessToken value by calling the following mfp function, even the bad response also not show:
WLAuthorizationManager.obtainAccessToken(userLoginChallengeHandler.securityCheckName).then(
function (accessToken) {
WL.Logger.debug("obtainAccessToken onSuccess");
showProtectedDiv();
},
function (response) {
WL.Logger.debug("obtainAccessToken onFailure: " + JSON.stringify(response));
showLoginDiv();
});
However, everything will be smooth if I remove my scope-elements mapping and mandatory application scope in mfp console.
For your information, I keep seeing this in my mfp log:
[2/10/21 22:52:17:035 MYT] 00000289 p.server.security.internal.context.ClientSecurityContextImpl E FWLSE4054E: Failed to externalize the security checks. The security checks are deleted for client: bdfe187e-f881-4678-a65a-335de2f0a427
java.io.NotSerializableException: java.util.logging.Logger
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.LinkedList.writeObject(LinkedList.java:1131)
at sun.reflect.GeneratedMethodAccessor501.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1128)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1577)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:351)
at com.ibm.mfp.server.security.internal.context.SecurityChecksState.toExternalString(SecurityChecksState.java:114)
at com.ibm.mfp.server.security.internal.context.SecurityChecksState.toExternalString(SecurityChecksState.java:29)
at com.ibm.mfp.server.security.internal.context.ExternalState.buildDataItemFromCurrentState(ExternalState.java:90)
at com.ibm.mfp.server.security.internal.context.ExternalState.store(ExternalState.java:68)
at com.ibm.mfp.server.security.internal.context.ClientSecurityContextImpl.store(ClientSecurityContextImpl.java:270)
at sun.reflect.GeneratedMethodAccessor276.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy165.store(Unknown Source)
at com.ibm.mfp.server.persistency.internal.transaction.StorageManagerImpl.storeLayer(StorageManagerImpl.java:79)
at com.ibm.mfp.server.persistency.internal.transaction.StorageManagerImpl.doWithStorage(StorageManagerImpl.java:61)
at com.ibm.mfp.server.security.internal.rest.PreAuthorizationEndpoint.authorize(PreAuthorizationEndpoint.java:78)
at sun.reflect.GeneratedMethodAccessor434.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1287)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1158)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:81)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:928)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:262)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:955)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:341)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:470)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:404)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:284)
at com.ibm.ws.http.channel.internal.inbound.HttpICLReadCallback.complete(HttpICLReadCallback.java:66)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:504)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:574)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:929)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1018)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
I tried to google for these, but cant get any answer, is it my configuration having some problem?
I tried to troubleshoot for this for weeks, but until now cant get any clue. Hope someone can help me please.
For your information, this is my scope element mapping from my mfp console:
WLAuthorizationManager.obtainAccessToken(userLoginChallengeHandler.securityCheckName).then(
function (accessToken) {
WL.Logger.debug("obtainAccessToken onSuccess");
showProtectedDiv();
},
function (response) {
WL.Logger.debug("obtainAccessToken onFailure: " + JSON.stringify(response));
showLoginDiv();
});
In the above API you are passing a scope which is name of your security check. If the client is already logged-in or is in the remembered state, the API triggers a success. If the client is not logged in, the security check sends back a challenge.
The reason why you see handleChallenge() function is being called because your user login success state has expired. Handle the challenge accordingly and call submitChallengeAnswer() API to submit the answer when handleChallenge() function is called.
If you don't pass scope in WLAuthorizationManager.obtainAccessToken() API you won't be challenged even if login success state has expired
For more details read here : https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/user-authentication/javascript/

Unable to authenticate using Kerberos Keytab and kinit cache

I am using a keytab and setting it up using the kinit command on my windows commandline. I get the message "New ticket is stored in cache file".After that when I run my java application to access the keytab file for the key I get below error.
Authentication attempt failed javax.security.auth.login.LoginException: No key to store
javax.security.auth.login.LoginException: No key to store
at com.sun.security.auth.module.Krb5LoginModule.commit(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.access$000(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
I am trying to connect to the active directory using ldap. Below are the configuration settings:
-Djavax.security.auth.useSubjectCredsOnly=false
-Djava.security.auth.login.config=C:\Users\cXXXXXX\Git\gssapi_jaas.conf
-Dsun.security.krb5.debug=true
Debug is true storeKey true useTicketCache true useKeyTab true doNotPrompt true ticketCache is null isInitiator true KeyTab is
C:\Users\cXXXXXX\Git\abcd.keytab refreshKrb5Config is false principal is xxxx_dev#xxxx.xxxxxx.COM tryFirstPass is false useFirstPass is false storePass is false clearPass is false
Acquire TGT from Cache
KinitOptions cache name is C:\Users\cXXXXXX\krb5cc_cXXXXXX
DEBUG client principal is xxxx_dev#xxxx.xxxxxx.COM
DEBUG server principal is krbtgt/xxxx.xxxxxx.COM#Txxxx.xxxxxx.COM
DEBUG key type: 23
DEBUG auth time: Mon Jul 01 14:20:21 EDT 2019
DEBUG start time: Mon Jul 01 14:20:21 EDT 2019
DEBUG end time: Tue Jul 02 00:20:21 EDT 2019
DEBUG renew_till time: null
CCacheInputStream: readFlags() INITIAL; PRE_AUTH;
Host address is /xx.xx.xxx.xx
Host address is /xxx:0:0:0:xxxx:xxxx:xxxx:xxxx
KrbCreds found the default ticket granting ticket in credential cache.
Java config name: null
Native config name: C:\windows\krb5.ini
Obtained TGT from LSA: Credentials:
client=sxxxx_dev#xxxx.xxxxxx.COM
server=krbtgt/Txxxx.xxxxxx.COM#Txxxx.xxxxxx.COM
authTime=20190701182021Z
startTime=20190701182021Z
endTime=20190702042021Z
renewTill=null
flags=INITIAL;PRE-AUTHENT
EType (skey)=23
(tkt key)=18
Principal is sxxxx_dev#xxxx.xxxxxx.COM
Before adding the kinit cache fil, I was able to atleast validate the account, then I was having issues with GSSapi security. Trying to resolve that I added the cache and this new problem started to happen
public static void main(String[] args) {
// 1. Log in (to Kerberos)
LoginContext lc = null;
try {
/*lc = new LoginContext(Azrm017.class.getName(),
new LuwCallBackHandler());
*/
lc = new LoginContext("Azrm017");
// Attempt authentication
// You might want to do this in a "for" loop to give
// user more than one chance to enter correct username/password
lc.login();
} catch (LoginException le) {
System.err.println("Authentication attempt failed " + le);
le.printStackTrace();
System.err.println("Authentication attempt failed " + le.getSuppressed());
System.exit(-1);
}
// 2. Perform JNDI work as logged in subject
NamingEnumeration<SearchResult> ne =
(NamingEnumeration<SearchResult>) Subject.doAs(lc.getSubject(),
new SearchAction());
while(ne.hasMoreElements()) {
System.out.println(">>>> : " + ne.nextElement().getName());
}
//Subject.doAs(lc.getSubject(), new JndiAction(args));
}
}
/**
* The application must supply a PrivilegedAction that is to be run
* inside a Subject.doAs() or Subject.doAsPrivileged().
*/
class SearchAction implements java.security.PrivilegedAction {
public Object run() {
// Set up the environment for creating the initial context
Hashtable<String, String> env = new Hashtable<> (11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
String cn = "dn:CN=xxxxxxx,OU=Service xxxxx,OU=Accounts,OU=xxxxx,DC=test,DC=xxxxxx,DC=com";
env.put(Context.PROVIDER_URL, "ldap://test.xxxxxxx.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put("javax.security.sasl.server.authentication", "true");
env.put("javax.security.sasl.qop", "auth-conf");
DirContext ctx = null;
try {
// Create initial context
ctx = new InitialDirContext(env);
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(
new String[] {"displayName", "mail","description", "suSunetID"});
NamingEnumeration<SearchResult> answer =
ctx.search("cn=People, dc=test, dc=xxxxxxxx, dc=com",
"(&(cn=p*)(sn=s*))", ctls);
return answer;
} catch (Exception e) {
e.printStackTrace();
}
// Close the context when we're done
finally {
closeContext(ctx);
}
return null;
}
Attached above
This is a wrong combination of Krb5LoginModule options. If you want an initiator to store a key then that key must be used to acquire the ticket (i.e. useTicketCache should not be true).
Why do you want to store the key? Will the initiator also act as an acceptor? If yes, you should either use the keytab to authenticate (i.e. useTicketCache=false) or go with the ENC-TKT-IN-SKEY way (i.e. storeKey=false).

Negotiate Header was invalid error with Spring Security Kerberos extension/IE, Firefox/AD

We are configuring Spring Security Kerberos extension in OWF 7 (Ozone Widget Framework) on JBoss AS 7.1.1. We see the following error:
23:01:44,172 WARN [org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter] (http--10.200.69.103-8080-2) Negotiate Header was invalid: Negotiate TlRMTVNTUAABAAAAl4II4gAAAAAAAAAAAAAAAAAAAAAGAbEdAAAADw==: org.springframework.security.authentication.BadCredentialsException: Kerberos validation not succesfull
at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.validateTicket(SunJaasKerberosTicketValidator.java:69) [spring-security-kerberos-core-1.0.0.M2.jar:]
at org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider.authenticate(KerberosServiceAuthenticationProvider.java:86) [spring-security-kerberos-core-1.0.0.M2.jar:]
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:120) [spring-security-core-3.0.2.RELEASE.jar:]
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48) [spring-security-core-3.0.2.RELEASE.jar:]
at org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter.doFilter(SpnegoAuthenticationProcessingFilter.java:131) [spring-security-kerberos-core-1.0.0.M2.jar:]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [org.springframework.web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [org.springframework.web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31]
Caused by: java.security.PrivilegedActionException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.6.0_31]
at javax.security.auth.Subject.doAs(Subject.java:396) [rt.jar:1.6.0_31]
at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.validateTicket(SunJaasKerberosTicketValidator.java:67) [spring-security-kerberos-core-1.0.0.M2.jar:]
... 23 more
Caused by: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
at sun.security.jgss.GSSHeader.<init>(GSSHeader.java:80) [rt.jar:1.6.0_31]
at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:287) [rt.jar:1.6.0_31]
at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:267) [rt.jar:1.6.0_31]
at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:146) [spring-security-kerberos-core-1.0.0.M2.jar:]
at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:136) [spring-security-kerberos-core-1.0.0.M2.jar:]
... 26 more
I saw a post on stack overflow ("Defective token detected" error (NTLM not Kerberos) with Kerberos/Spring Security/IE/Active Directory) and thought someone can help me with our situation.
Our setup:
JDK 1.6.0_31
JBoss AS 7.1.1.Final running on Red Hat Enterprise Linux Server release 6.2 (Santiago) Kernel 2.6.32-220.el6.x86_64 on an x86_64
Windows Server 2008 Active Directory
Spring Security Kerberos Extension M2 (configured following the instructions provided in their blog: http://blog.springsource.com/2009/09/28/spring-security-kerberos/ )
Firefox 21 (runs on a VM)
IE 10 (runs on a VM)
From the previous post listed above it appears like AD server is sending an NTLM token to IE and IE is sending this to application. We have our Application Server (JBoss), AD Server and client (IE, Firefox) on different machines
joined to the same domain. Below is the krb5.conf file from /etc folder of the linux box where JBoss is:
[libdefaults]
default_realm = ENTERPRISELABS.MYCOMPANY.COM
default_tgs_enctypes = aes256-cts aes128-cts arcfour-hmac-md5 des-cbc-md5 des-cbc-crc
default_tkt_enctypes = aes256-cts aes128-cts arcfour-hmac-md5 des-cbc-md5 des-cbc-crc
permitted_enctypes = aes256-cts aes128-cts arcfour-hmac-md5 des-cbc-md5 des-cbc-crc
dns_lookup_realm = true
dns_lookup_kdc = true
passwd_check_s_address = false
noaddresses = true
udp_preference_limit = 1
ccache_type = 3
kdc_timesync = 0
kdc_timesync = 0
[domain_realm]
.enterpriselabs.com = ENTERPRISELABS.MYCOMPANY.COM
enterpriselabs.com = ENTERPRISELABS.MYCOMPANY.COM
.cdc.lab = ENTERPRISELABS.MYCOMPANY.COM
cdc.lab = ENTERPRISELABS.MYCOMPANY.COM
.dcas-i-2-069103 = ENTERPRISELABS.MYCOMPANY.COM
.enterpriselabs.mycompany.com = ENTERPRISELABS.MYCOMPANY.COM
dcas-i-2-069103 = ENTERPRISELABS.MYCOMPANY.COM
enterpriselabs.mycompany.com = ENTERPRISELABS.MYCOMPANY.COM
mcc-ad01.enterpriselabs.mycompany.com = ENTERPRISELABS.MYCOMPANY.COM
mcc-ad03.enterpriselabs.mycompany.com = ENTERPRISELABS.MYCOMPANY.COM
scr0-i-1-069137.scr0.enterpriselabs.mycompany.com = SCR0.ENTERPRISELABS.MYCOMPANY.COM
ssbox8.cdc.lab = ENTERPRISELABS.MYCOMPANY.COM
[realms]
ENTERPRISELABS.MYCOMPANY.COM = {
kdc = mcc-ad01.enterpriselabs.mycompany.com:88
master_kdc = mcc-ad01.enterpriselabs.mycompany.com:88
kpasswd = mcc-ad01.enterpriselabs.mycompany.com:464
kpasswd_server = mcc-ad01.enterpriselabs.mycompany.com:464
kdc = mcc-ad03.enterpriselabs.mycompany.com:88
master_kdc = mcc-ad03.enterpriselabs.mycompany.com:88
kpasswd = mcc-ad03.enterpriselabs.mycompany.com:464
kpasswd_server = mcc-ad03.enterpriselabs.mycompany.com:464
}
SCR0.ENTERPRISELABS.mycompany.COM = {
kdc = scr0-i-1-069137.scr0.enterpriselabs.mycompany.com:88
master_kdc = scr0-i-1-069137.scr0.enterpriselabs.mycompany.com:88
kpasswd = scr0-i-1-069137.scr0.enterpriselabs.mycompany.com:464
kpasswd_server = scr0-i-1-069137.scr0.enterpriselabs.mycompany.com:464
}
Under [domain_realm] block the first 2 entries won't have .mycompany in them. Is this a problem?
We generated the keytab file by running the following command:
ktpass /princ HTTP/jaguar.enterpriselabs.mycompany.com#ENTERPRISELABS.MYCOMPANY.COM /mapuser jaguar#ENTERPRISELABS.MYCOMPANY.COM -crypto all -pass password -ptype KRB5_NT_PRINCIPAL -out c:\jaguar-host.keytab
We copied the keytab file generated to the WEB-INF/classes folder of our application on JBoss. When we contacted our tech support they also mentioned that test user accounts created have 'Kerberos Authentication'
checkbox checked. I think when we login to the domain we are authenticated using kerberos not NTLM (I don't know whether it is correct or not). But, this didn't help us getting rid of the above problem.
I used fiddler and saw 'NTLM Authentication' in one of the screens. Please help us in debugging this problem. I think the problem is in AD somewhere and don't know where to look for answers. Do we have to follow any specific
steps to make sure our AD is configured right? Is there a way to configure AD server to send Kerberos token?
Are you sure that jaguar.enterpriselabs.mycompany.com is DNS A record hostname instead of CNAME alias?
I think I had a similar error message when I created the keytab using a DNS alias hostname (CNAME).
When browser asks KDC for the ticket, it always uses the DNS A record hostname, regardless of the hostname you have in browser address bar. Users can still use CNAME alias hostnames to access the site, but the keytab must be created using A record hostname.