WebAPI EnableCors with SupportsCredentials = true not working - asp.net-web-api

I have an MVC site deployed to mysite.mydomain.co that authenticates against ADFS and creates an auth cookie:
public partial class Startup
{
public void ConfigureUserAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
});
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
MetadataAddress = ConfigurationManager.AppSettings["adsfs.MetadataAddress"],
Wtrealm = ConfigurationManager.AppSettings["adsfs.Wtrealm"]
});
}
}
There is also a WebAPI site deployed on "myapi.mydomain.com" with CORS enabled:
GlobalConfiguration.Configuration.EnableCors(new EnableCorsAttribute("https://mysite.mydomain.com", "*", "*") { SupportsCredentials = true });
The the user goes to mysite.mydomain.com. The MVC site authenticates against ADFS and I see the auth cookie being set with no problem.
My application is mostly an SPA, so from javascript there's a AJAX calls to myapi.mydomain.com using jQuery, setting the withCredentials option to true:
$.ajaxSetup({
xhrFields: { withCredentials: true }
});
That options is supposed to send security credentials (cookies) to the API. At runtime I don't see the cookies being set to the API and I get a 401 (unauthorized) error as expected.
If I run the same code on localhost (except for changing the origins to localhost of course) I see the cookie flowing to the API with no problem. My best guess is it works because it's the same subdomain (localhost) whereas on my servers is "mysite" vs "myapi".
Any ideas?

Related

How should I set net core api cors?

I am coding an unofficial twitter api for myself. Then I send a get to this api using the console screen in my browser with the following method.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
such
httpGet(https://localhost:44311/WeatherForecast/alienationxs/true);
the problem is that when i do this via www.google.com it's ok and json data reaches me. but when I do it via twitter.com I get the following error.
via google.com
my cors settings on api
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
options.AddDefaultPolicy(builder =>
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); ;
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "twitterAPI", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "twitterAPI v1"));
}
app.UseRouting();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
all i want is to reach my api via twitter.com just like google.com.
First, let's separate the flies from the cutlets.
Cross-Origin Resource Sharing (CORS) - is a separate security layer.
Content Security Policy (CSP) - is a separate security layer, it's appied before CORS. After passing through CSP yous can face with CORS if last one is breached.
As you can see from error message "... because it violates the following Content Security Policy directive ...", you faced with CSP violation therefore your CORS settings have no mean.
What's goin on.
You enter twitter.com web page and tries to execute connect request to localhost:44311 on behalf of twitter web page. But twitter's web page protected by CSP which forbid such requests:
Pay attention on 'connect-src' directive, which governs XMLHttpRequest().
The www.google.com web page does not have CSP, therefore you request on behalf of google does success.
The Twitter API does not support CORS.

Session cookie is not set in browser

I have frontend client running on custom Next.js server that is fetching data with apollo client.
My backend is graphql-yoga with prisma utilizing express-session.
I have problem with picking correct CORS settings for my client and backend so cookie would be properly set in the browser, especially on heroku.
Currently I am sending graphql request from client with apollo-client having option
credentials: "include" but also have tried "same-origin" with no better result.
I can see cookie client in response from my backend in Set-Cookie header, and in devTools/application/cookies. But this cookie is transparent to browser and is lost on refresh.
With this said I also tried to implement some afterware to apollo client as apolloLink that would intercept cookie from response.headers but it is empty.
So far now I'm thinking about pursuing those two paths of resolving the issue.
(I'm only implementing CORS because browser prevents fetching data without it.)
CLIENT
ApolloClient config for client-side:
const httpLink = new HttpLink({
credentials: "include",
uri: BACKEND_ENDPOINT,
});
Client CORS usage and config:
app
.prepare()
.then(() => {
const server = express()
.use(cors(corsOptions))
.options("*", cors(corsOptions))
.set("trust proxy", 1);
...here goes rest of implementation
const corsOptions = {
origin: [process.env.BACKEND_ENDPOINT, process.env.HEROKU_CORS_URL],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie", '*'],
methods: "GET,POST",
optionsSuccessStatus: 200
};
My atempt to get headers from response in apolloClient(but headers are empty and data is not fetched afterwards):
const middlewareLink = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
const context = operation.getContext();
const {response: {headers}} = context;
if (headers) {
const cookie = response.headers.get("set-cookie");
if (cookie) {
//set cookie here
}
}
return response;
});
});
BACKEND
CORS implementaion (remeber that is gql-yoga so I need first to expose express from it)
server.express
.use(cors(corsOptions))
.options("*", cors())
.set("trust proxy", 1);
...here goes rest of implementation
const corsOptions = {
origin: [process.env.CLIENT_URL_DEV, process.env.CLIENT_URL_PROD, process.env.HEROKU_CORS_URL],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie"],
exposedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie"],
methods: "GET,HEAD,PUT,PATCH,POST,OPTIONS",
optionsSuccessStatus: 200
};
Session settings, store is connect-redis
server.express
.use(
session({
store: store,
genid: () => uuidv4(v4options),
name: process.env.SESSION_NAME,
secret: process.env.SESSION_SECRET,
resave: true,
rolling: true,
saveUninitialized: false,
sameSite: false,
proxy: STAGE,
unset: "destroy",
cookie: {
httpOnly: true,
path: "/",
secure: STAGE,
maxAge: STAGE ? TTL_PROD : TTL_DEV
}
})
)
I am expecting session cookie to be set on the client after authentication.
Actual result:
Cookie is visible only in Set-Cookie response header but is transparent to browser and not persistent nor set (lost on refresh or page change). Funny enough I can still make authenticated requests for data.
This may not be a CORS issue, it looks like a third-party cookie problem.
Behaviour could be different across browsers so I recommend testing several ones. Firefox (as of version 77) seems to be less restrictive. In Chrome (as of version 83) there is an indicator on the far right of the URL bar when a third party cookie has been blocked. You can confirm whether third party cookies is the cause of the problem by creating an exception for the current website.
Assuming your current setup is as follows:
frontend.com
backend.herokuapp.com
Using a custom domain for your backend that is a subdomain of your frontend would solve your problem:
frontend.com
api.frontend.com
The following setup wouldn't work because herokuapp.com is included in the Mozilla Foundation’s Public Suffix List:
frontend.herokuapp.com
backend.herokuapp.com
More details on Heroku.

How do I log out of Stormpath ID Site with express-stormpath and stormpath-sdk-angularjs?

I have an express-stormpath application that uses Stormpath ID Site. It has this configuration:
app.use(stormpath.init(app, {
web: {
idSite: {
enabled: true,
uri: '/idSiteResult',
nextUri: '/'
},
login: {
enabled: true,
uri: config.login
},
logout: {
enabled: true,
uri: config.logout
},
me: {
expand: {
customData: true,
groups: true
}
}
}
}));
Login works fine, but logout is giving me trouble.
First, I tried logging out with the stormpath-sdk-angularjs built-in endSession()
$auth.endSession();
But I was still logged in.
Digging into express-stormpath, it looks like logout POST requires Accept type text/html for id-site logout. In stormpath-sdk-angularjs, it looks like endSession POST uses application/json.
So I tried logging out with $http.post
$http.post('/logout', null, {
headers: {
'Accept': 'text/html'
}
});
But I get this error:
XMLHttpRequest cannot load https://api.stormpath.com/sso/logout?jwtRequest=[...]. Redirect from 'https://api.stormpath.com/sso/logout?jwtRequest=[...]' to 'http://localhost:9000/idSiteResult?jwtResponse=[...]' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
How do I log out of Stormpath ID Site?
I work at Stormpath. ID Site requires that you actually redirect the end user to ID Site. I'm not sure why endSession() isn't working, but I'll reach out to our JS team to see if there might be a bug there.
In the meantime, you can use this code (or the equivalent in Angular-specific primitives) to accomplish a logout:
var form = document.createElement('form');
form.method = "POST";
form.action = "/logout";
form.submit();
This looks like a CORS issue. I believe you need to add at least;
Access-Control-Allow-Origin: https://api.stormpath.com
To the response headers from your server.

Cookie is "undefined" in Koa/Express request

I'm using Koa JS framework for jwt authentication.
So basically when the user signs in, I set a jwt token (signed) to user's browser cookie, which seems to work fine as shown below (Chrome cookie settings):
(www.localhost.com instead of localhost is because I edited my hostfile, but this should have no effect in setting/getting cookies)
The problem, however, is when I send a POST request to my local Koa server, the jwt cookie is undefined. All I'm doing to verify the token is this:
routes.js
const Router = require("koa-router");
const router = new Router();
router.post(`api/authenticate`, function* () {
const jwt = this.cookies.get("jwt", { signed: true }); //jwt is undefined!!
if (!jwt)
this.throw("Invalid or expired token!");
this.status = 200;
});
//...
app.use(router.routes());
app.use(router.allowedMethods());
Here, this.cookies.get("jwt") returns undefined. The POST request is sent using AXIOS library with "withCredentials: true" header and a valid CSRF token:
authenticate.js
axios.post("api/authenticate", {}, {
headers: {
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": "A VALID CSRF TOKEN GENERATED BY SERVER",
"Content-Type": "application/json",
},
withCredentials: true,
});
Can anyone help me find out why this.cookies.get fails to fetch cookie from a simple POST request? I'm simply posting to my localhost, so I believe this is not a CORS problem.
What is more strange is that when I check my chrome developer tool, the "jwt" and "jwt.sig" tokens are successfully included in the request header..
Any help would be appreciated.
Update: Setting the cookie
//...
this.cookies.set("jwt", "SOME JWT GENERATED BY SERVER", {
httpOnly: true,
signed: true,
});
//...

Request with token from ADAL for Cordova returns 401 response from Web Api

I'm hoping someone can help with this:
I have a web api secured with Azure AD Bearer Authentication, where I have two web clients that can successfully authenticate on the web api using bearer tokens from AD. The Web API and both web applications are configured as applications in AD. I've tried to use ADAL for Cordova for accessing the web api a iOS/Android app but it's returning 401.
ClaimsPrincipal.Current.Identity.IsAuthenticated is returning false.
I'm using the client id for the native application I've setup in Azure AD, and I'm receiving the token but this token is invalid. After I've parsed the token on jwt.io, everything seems correct but I've noticed the token doesn't have a header.
I've added permissions to access the Web Api and sign in and access AD as the user.
The code I'm using in Cordova is below, the authority I'm using is the same as the other apps that are working. Where resource is the app Id for the Web Api in AD, and client id is the client id for the native app in Azure Ad.
// Attempt to authorize user silently
AuthenticationContext.acquireTokenSilentAsync(resource, clientId)
.then(function (result) {
sessionService.logIn(result.idToken);
console.log(result);
deferred.resolve();
}, function () {
// We require user credentials so triggers authentication dialog
AuthenticationContext.acquireTokenAsync(resource, clientId, redirectUri)
.then(function (result) {
console.log(result);
sessionService.logIn(result.idToken);
deferred.resolve();
}, function (err) {
console.log("Failed to authenticate" + err);
deferred.reject("failed to authenticate");
});
});
I've also tried using result.accessCode, which also doesn't work.
StartUp.Auth.cs in Web Api:-
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudiences = Audiences
}
});
}
Can anyone help please?
Thanks
You appear to be sending the wrong token to the API - you are supposed to send result.accessToken. See https://github.com/Azure-Samples/active-directory-cordova-multitarget/blob/master/DirSearchClient/js/index.js for an example.

Resources