Single page application with HttpOnly cookie-based authentication and session management - reactjs

For several days now I've been looking for a secure authentication and session management mechanism for my single page application. Judging by the numerous tutorials and blog posts out there about SPAs and authentication, storing JWTs in localStorage or regular cookies seems to be the most common approach, but it's simply not a good idea to use JWTs for sessions so it's not an option for this app.
Requirements
Logins should be revokable. For example, if suspicious activity is detected on a user's account, it should be possible to revoke that user's access immediately and require a new log in. Similarly, things like password resets should revoke all existing logins.
Authentication should happen over Ajax. No browser redirection ("hard" redirection) should take place afterwards. All navigation should happen inside the SPA.
Everything should work cross-domain. The SPA will be on www.domain1.com and the server will be on www.domain2.com.
JavaScript should have no access to sensitive data sent by the server, such as session IDs. This is to prevent XSS attacks where malicious scripts can steal the tokens or session IDs from regular cookies, localStorage or sessionStorage.
The ideal mechanism seems to be cookie-based authentication using HttpOnly cookies that contain session IDs. The flow would work like this:
User arrives at a login page and submits their username and password.
The server authenticates the user and sends a session ID as an HttpOnly response cookie.
The SPA then includes this cookie in subsequent XHR requests made to the server. This seems to be possible using the withCredentials option.
When a request is made to a protected endpoint, the server looks for the cookie. If found, it cross-checks that session ID against a database table to make sure the session is still valid.
When the user logs out, the session is deleted from the database. The next time the user arrives on the site, the SPA gets a 401/403 response (since the session has expired), then takes the user to the login screen.
Because the cookie has the HttpOnly flag, JavaScript would not be able to read its contents, so it would be safe from attacks as long as it is transmitted over HTTPS.
Challenges
Here's the specific issue I've run into. My server is configured to handle CORS requests. After authenticating the user, it correctly sends the cookie in the response:
HTTP/1.1 200 OK
server: Cowboy
date: Wed, 15 Mar 2017 22:35:46 GMT
content-length: 59
set-cookie: _myapp_key=SFMyNTYBbQAAABBn; path=/; HttpOnly
content-type: application/json; charset=utf-8
cache-control: max-age=0, private, must-revalidate
x-request-id: qi2q2rtt7mpi9u9c703tp7idmfg4qs6o
access-control-allow-origin: http://localhost:8080
access-control-expose-headers:
access-control-allow-credentials: true
vary: Origin
However, the browser does not save the cookie (when I check Chrome's local cookies it's not there). So when the following code runs:
context.axios.post(LOGIN_URL, creds).then(response => {
context.$router.push("/api/account")
}
And the Account page is created:
created() {
this.axios.get(SERVER_URL + "/api/account/", {withCredentials: true}).then(response => {
//do stuff
}
}
This call does not have the cookie in the header. The server therefore rejects it.
GET /api/account/ HTTP/1.1
Host: localhost:4000
Connection: keep-alive
Accept: application/json
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,tr;q=0.6
Do I need to do something special to make sure the browser saves the cookie after receiving it in the login response? Various sources I've read have said that browsers save response cookies only when the user is redirected, but I don't want any "hard" redirects since this is an SPA.
The SPA in question is written in Vue.js, but I guess it applies to all SPAs. I'm wondering how people handle this scenario.
Other stuff I've read on this topic:
SPA best practices for authentication and session management
Are HTTPOnly Cookies submitted via XmlHTTPRequest with withCredentials=True?
Stop using JWT for sessions, part 2: Why your solution doesn't work

I got this working on Vue.js 2 with credentials = true. Setting credentials from client site only half of the story. You need to set response headers from the server as well:
header("Access-Control-Allow-Origin: http://localhost:8080");
header("Access-Control-Allow-Credentials: true");
You can't use wildcard for Access-Control-Allow-Origin like this:
header("Access-Control-Allow-Origin: *");
When you specify the credentials: true header, you are required to specify the orgin.
As you can see, this is a PHP code, you can model it to NodeJS or any server side scripting language you are using.
In VueJS I set credentials = true like this in the main.js:
Vue.http.options.credentials = true
In the component, I successfully logged in using ajax:
<template>
<div id="userprofile">
<h2>User profile</h2>
{{init()}}
</div>
</template>
<script>
export default {
name: 'UserProfile',
methods: {
init: function() {
// loggin in
console.log('Attempting to login');
this.$http.get('https://localhost/api/login.php')
.then(resource => {
// logging response - Notice I don't send any user or password for testing purposes
});
// check the user profile
console.log('Getting user profile');
this.$http.get('https://localhost/api/userprofile.php')
.then(resource => {
console.log(resource.data);
})
}
}
}
</script>
On the server side, things are pretty simple:
Login.php on sets a cookie without making any validation whatsoever (Note: this is done for testing purposes only. You are not advised to use this code in production without validation)
<?php
header("Access-Control-Allow-Origin: http://localhost:8080");
header("Access-Control-Allow-Credentials: true");
$cookie = setcookie('user', 'student', time()+3600, '/', 'localhost', false , true);
if($cookie){
echo "Logged in";
}else{
echo "Can't set a cookie";
}
Finally, the userprofile.php just verifies if a cookie = user is set
<?php
header("Access-Control-Allow-Origin: http://localhost:8080");
header("Access-Control-Allow-Credentials: true");
if(isset($_COOKIE['user'])){
echo "Congratulations the user is ". $_COOKIE['user'];
}else{
echo "Not allowed to access";
}
Successfully logged in

With credentials controls setting and sending cookies so be sure to turn it on when posting to login so the returned cookie is saved in the browser.

Related

Token refresh fails with invalid_client error

I have a refresh token issued by app A. This refresh token is stored in an Azure Key Vault, to which app B has access. App B now takes this refreh token and exchanges it for an access token.
Unfortunately this exchange fails with the message
"error": "invalid_client",
"error_description": "AADSTS7000215: Invalid client secret is provided."
The client secret is correct though. I was able to acquire an access token to the Key Vault with it.
This is the HTTP request for the refresh token exchange taken from Fiddler (I have removed all secrets and ids):
POST https://login.microsoftonline.com/{TenantId}/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.1.17763.134
Host: login.microsoftonline.com
Content-Length: 1221
Connection: Keep-Alive
grant_type=refresh_token
&client_id={ClientId}
&client_secret={ClientSecret}
&resource=https%3A%2F%2Fvault.azure.net
&redirect_uri=https%3A%2F%2Flocalhost%2F
&refresh_token={RefreshToken}
What is going here?
PS: I know it's wild storing a refresh token in a Key Vault, but that's Microsofts recommended way of accessing the CSP Partner API.
Same as the Rohit said, the resource should be the app that you want to access.
For the details about this, you could refer to here.

Azure AD automatically added offline_access

For Microsoft OAuth 2.0 auth code grant, we have encountered an issue with scopes.
When we requestion only the User.Read scope, our client is asked to grant permission to us for Sign you in and read your profile and Access your data anytime. Where we didn't state we need offline_access scope.
This is only happening after Microsoft switched to new permission grant interface. Have someone else encounter the same issue or we did something wrong?
The response_type we pass in is code only.
I have double checked, the application we registered is under https://apps.dev.microsoft.com.
The URL we use for authorizing is following.
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
As I said earlier, the only scope we pass in through query was User.Read.
Edit 3
Request URL: (I have removed client id.)
https://login.microsoftonline.com:443/common/oauth2/v2.0/authorize?client_id={client_id}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A19974%2Fapi%2Fv1%2Fmicrosoft%2Foauth2%2Fsession&response_mode=form_post&scope=User.Read&state=1527572151-IIZ0D&nonce=1527572151-IIZ0D&prompt=consent&domain_hint=organizations
Response that logged with fiddler:
POST http://localhost:19974/api/v1/microsoft/oauth2/session HTTP/1.1
Host: localhost:19974
Connection: keep-alive
Content-Length: 798
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: null
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en,en-NZ;q=0.9,zh-TW;q=0.8,zh;q=0.7,zh-CN;q=0.6
DNT: 1
code=OAQABAAIAAADX8GCi6Js6SK82TsD2Pb7rUmGhJoHUB3devvTffqTlhRhg9XZ202zgEA8B37CzgkeLNVBc4FFstw3sTjNmYhKCYLE_jcl7KeCrtYgPVFYOKUuazv_B3vHKIM8ttwIzOlV_3GL4vqxPgjvXbWUdas5Sj9Z1X9fEBB63Wa1Ig0AnisnHk6qagIimFEPApYx473RzgIve2erM3r5fnX5Q0L1-pHppSFUJoWop6MPTkUh-umPzuXQgB280rHyUds3odS6_cJP6SbI70aLNOqHV_AnaV_VUZqQ6hLfBZMVKFMYMg_r_harPOU5EE2gf2d15FIKMsmjPRTR2vryaJRyg0TblF_jr-kWyeURwpbkPzsU6r3avEqM6dfTqhhASoXB4VmeZ2zw75pZgK4v8cfcd3J_tIpFRjcEY1TqPz5E3QrYQGfFSeBEEbjwqvj2X5_4VBvve7ABdrt3OCjid8E_837mLX-Fv5t3nk_nfnV0SY6XrFQQmoPClyqSyn44FTv_WFY7Af74SfeBrWDYSSiTuwphEmVTeT6U2R4Rs4wR8G0uHW2L53U-4UbkODd-_-JZYIahAohDAF-8TaguUwb4mOK497wsFOkgpmYz-np4MX3sTweSLmn6bAOy9Y91E3o4fuERzX9m9N_HBt64cv6k8JROKJqs6cx1Gb9EoYCRLCn2ihWi_crZh2PH5LACMCLWYgH0gAA&state=1527572151-IIZ0D&session_state=1faeaab9-0f00-45cb-a776-356463a54684
Edit 4
Today, I have done few more testing while upgrading project to .Net Core 2.1. I have notice that even though from interface it is confirming Access your data anytime, but when I use code to exchange access token, it doesn't contain refresh token.
The other thing I have notice is, when I pass scope as User.Read, and when I exchange access token, the scope came back as: User.Read User.ReadBasic.All. This is a bit of inconsistent, but not big issue.
It’s not currently possible to remove the offline_access scope from the initial consent screen when using the v2 endpoint with an AAD account. When requesting tokens the offline_access scope is still explicitly requested though.
This is an issue which is in a planned state on Azure Active Directory suggestions and feedback site.
Admin's post (Oct 2, 2018) mentions a plan to fix this "within the next 3 months".
Cuase:
For v1 endpoint, the scope isstatically configured in AAD App registration. If you have add access user's data anytime permission, you will also get the offline_access scope in your request.
Solution:
If you don't want to let user have offline_access permission, you can unpick up the Access user's data anytime permission in Microsoft Graph delegated permissions.
More about offline_access :
offline_access is one of OpenID permissions. It's name is offline_access and it's Display String in v1 endpoint is Access user's data anytime.You can see more details about this permission in this documentation.

Is there a way to use oauth for GAE using postman

We're using postman to test our service APIs running on GAE. In order to authentication, we have to add a header value 'X-Auth' and copy the oauth authentication token used for our login (retrieved from google javascript library). We have to do this a lot because the token is rather short lived, so it's a real pain/bottleneck for our developers.
I've been looking into using the postman oauth authentication and even got it working... sort of. I successfully configured the oauth and logged myself in, granting the permissions, etc and received a token. However postman wants to put this token into the header not as 'X-Auth' but as 'Bearer' and for whatever reason, authentication is failing. Perhaps it's because the header name is wrong, perhaps I'm also getting the wrong token value.
So: Has anyone had success using postman with oauth on GAE?
PS, here's the 'code' Postman is generating :
GET /api/XXX/ST_W HTTP/1.1
Host: admin.mycompany.com:8080
Accept-Encoding: application/json
Authorization: Bearer ya29.GmDtA-o7ahRzDFl_kMQZD8n7Y3b38TUg58u3kon6t64JifRhOWNBBd8nsuSJ5-OcZW76xC8j3l9EN39D7Z0860qm1S6IwwwdX0AAvXmQwJZg_mXKQH1r9YZOLmgA95dq9_M
Cache-Control: no-cache
Postman-Token: a2182695-9b56-1834-5312-3885f2d77426

angular HTTP auth: not getting browser login prompt

In my angular app, i am trying to do basic HTTP auth.
I send the http get request from angular without any credentials initially, as i assume that when the backend sends a 401 status, the browser would ask me for credentials and would then resubmit the request on its own.
But the browser login prompt is never displayed.
This is the error that i get:
angular.js:11756 GET http://localhost:8080/appName/rest/keys/Keys?batch=0&userName=Test 401 (Unauthorized)
These are the headers i get for response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, content-type, accept, authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:3001/
Content-Length:0
Date:Tue, 09 Aug 2016 14:53:26 GMT
Server:Apache-Coyote/1.1
WWW-Authenticate:Basic
I was hoping that the browser prompt would appear automatically when it encounters status 401, but it doesn't seem to be the case here. Am i missing something?
EDIT:
It does not work in Chrome and Firefox, but works in IE, IE displays a login prompt when i try to access the url, and works correctly with username and password, while Chrome directly gives a 401 error.
If i try to access the server url directly from address bar, then Chrome displays the login prompt and asks me for the credentials.
Not sure, but can it be a CORS issue?
Ok, i was able to resolve the issue.
The problem was indeed related to CORS, not in a direct way.
Also, it was working on IE since IE does not respect CORS and will anyways let you access cross origin.
Two things were missing:
Initially i was sending (along with other headers) Access-Control-Allow-Origin : * from the server, for enabling CORS.
Then i got to know this:
Firefox and Chrome require exact domain specification in
Access-Control-Allow-Origin header. For servers with authentication,
these browsers do not allow "*" in this header. The
Access-Control-Allow-Origin header must contain the value of the
Origin header passed by the client.
https://www.webdavsystem.com/ajax/programming/cross_origin_requests/
And then there was an issue related to cross origin browser auth:
By default, in cross-site XMLHttpRequest invocations, browsers will
not send credentials. A specific flag has to be set on the
XMLHttpRequest object when it is invoked.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials
This specific flag is withCredentials : true, which needs to be set with the xhr request. I managed to set it with my http request from the angular app, and voila it worked!

Why does Salesforce OAuth2 redirect me from one instance na3 for ex to another na9

I am trying to build a web app that lets the customer add demo data to any Salesforce instance. My demo builder uses OAuth 2 Authorization Code Grant.
I am trying to get the switch instance portion working. However once the user connects to one instance
GET /services/oauth2/authorize?response_type=code&client_id=blabla.UKP&redirect_uri=https%3A%2F%2Fsfblademo.bla.com%2Foauth%2Fcallback HTTP/1.1
Host: na9.salesforce.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.12 Safari/535.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: cookie_bla; disco=5:00D50000000Ii39:00550000001ifEp:0|; autocomplete=1; inst=APP5
It redirects to the previous instance. Seems like its reading cookies and redirecting
HTTP/1.1 302 Found
Server:
Location: https://na3.salesforce.com/setup/secur/RemoteAccessAuthorizationPage.apexp?source=blablabla
Content-Type: text/html
Content-Length: 525
Date: Fri, 16 Sep 2011 21:46:58 GMT
The URL has moved here
Is there a way to sign out or clear the cookies salesforce has. I am not running my app on salesforce.
Thanks !
The API logout() call isn't going to work because that will only invalidate the API session and not the UI session stored in the browser cookie on the *.salesforce.com domain, to which your app won't have direct access. That's not to say it isn't still recommended, but to clear that UI cookie, you'll need to redirect the end user to /secur/logout.jsp on the instance_url of the previous session. To make it transparent to end users, you can load it in a hidden iframe like this:
<iframe src='https://{instance_url}/secur/logout.jsp' width='0' height='0' style='display:none;'></iframe>
Before switching to other instance, you can try making the logout call, as described here WS Guide :http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_logout.htm
This will invalidate the previous session hopefully..

Resources