I’m using Kotlin for the first time and am creating a android front end for my NodeJS backend and MongoDB Database.
Currently, I’m developing the authentication logic on my front end and it seems to be working for Login and Logout. Since I used session and cookies for my authentication in my backend I have also set that up in my android app.
My specific issue resides in next requests that I make after Logging In. Specifically, in this case fetching my inventory. My backend is denying the access, stating the 401 Error Code: Unauthorized.
After setting up some logs, I seem to see that my cookie is nowhere to be found when requesting.
My question is this, Is the way I implemented my SessionCookieJar correct? or are am I missing some steps in my implementations
Here are my codes:
SessionCookieJar.kt
object SessionCookieJar {
private val cookieStore: MutableMap<String, List<Cookie>> = mutableMapOf()
private val cookieJar = object : CookieJar {
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
println("Saving Cookies from response for URL: $url")
cookieStore[url.host] = cookies
println("Cookies: $cookies")
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookies = cookieStore[url.host] ?: emptyList()
println("Loading Cookies for request to URL: $url")
println("Cookies: $cookies")
return cookies
}
}
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.cookieJar(cookieJar)
.build()
private val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("link) // ngrok forwarding port
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService: ApiService = retrofit.create(ApiService::class.java)
fun printCookies() {
println("Stored Cookies:")
cookieStore.forEach { (host, cookies) ->
println("Host: $host")
cookies.forEach { cookie ->
println("Cookie: ${cookie.name}=${cookie.value}")
}
}
}
}
Inventory Service – Fetching Inventory
suspend fun fetchInventory(
filterStock: String? = null,
filterStatus: String? = null,
filterCategory: String? = null,
filterTags: String? = null,
sortType: String? = "createdAt",
sortOrder: String? = "1"
): List<Inventory> {
return try {
println("Fetching Inventory...")
val response = SessionCookieJar.apiService.fetchInventory(
filterStock, filterStatus, filterCategory, filterTags, sortType, sortOrder
)
SessionCookieJar.printCookies()
if (response.isSuccessful) {
response.body() ?: emptyList()
} else {
println("Response unsuccessful: ${response.code()}")
emptyList()
}
} catch (e: Exception) {
println("An Error Occurred (Fetch Inventory): $e")
emptyList()
}
}