Hello,
I’ve established a basic token based authentication workflow but I want to switch to a session-based workflow using cookies so that my client doesn’t have to keep stuffing a bearer token in each request.
I’m using Express JS on the server and for the sake of this Q&A, I’m running everything locally on my machine. My client is running on localhost:8000 and my server is running on localhost:3000 . I’m using the okta-auth-js SDK and the authClient.session.setCookieAndRedirect() method in simple JavaScript as my Hello World example below.
To the point:
Q1: How do I get Okta’s setCookieAndRedirect() to set an HttpOnly cookie in my domain vs the oktapreview domain?
I see a cookie with the session ID set in the mydomain.oktapreview.com domain using my browser but I don’t see it in my current application’s domain. As such, when I submit a call to my back-end API from my application domain, there is no cookie seen by the server.
Q2: Should my server expect to see a session ID in a request’s HttpOnly cookie?
Here’s what I’ve done in the client. At this point, all the server does is dump out the request headers and cookies:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/1.8.0/okta-auth-js.min.js" type="text/javascript"></script>
<script type="text/javascript">
var authClient = new OktaAuth({
responseType: ['token','id_token'],
scopes: ['openid','email'],
url: 'https://mydomain.oktapreview.com',
clientId: 'my-client-id',
responseMode: 'fragment',
redirectUri: 'http://localhost:8000',
issuer: 'https://mydomain.oktapreview.com/oauth2/default'
});
function signInAndSetCookie() {
console.log('signInAndSetCookie()');
authClient.signIn({
username: 'mytestuser',
password: 'mytestuserspassword'
})
.then(function(transaction) {
// If successful, save the access and ID tokens in the tokenManager for easy retrieval later.
if (transaction.status === 'SUCCESS') {
console.log('transaction.sessionToken => ' + transaction.sessionToken);
authClient.session.setCookieAndRedirect(transaction.sessionToken,'http://localhost:8000/index.html');
} else {
throw 'We cannot handle the ' + transaction.status + ' status';
}
})
.fail(function(err) {
console.log("login fail: "+err.message)
console.error(err);
});
}
function listCatalogLocalhost() {
console.log('listCatalog()');
$.ajax({
url: 'http://localhost:3000/api/list/get_catalog',
success: function(response) {
// Received messages!
console.log('Messages', response);
},
error: function(response) {
console.error(response);
}
});
}
</script>
<body>
<a href="javascript:signInAndSetCookie()" id="signin">Sign In and Set Session Cookie</a><br>
<a href="javascript:listCatalogLocalhost()" id="loadlistslocalhost">Load Lists (localhost:3000)</a><br>
</body>
Your help would be greatly appreciated!!
–Ray
My citations and prior research:
Documentation
Prior related posts: