16

I have used OAuth cookie authentication in the ASP.NET Core API project. All the APIs are authorized in this project. After successful login, all APIs can be accessible from a browser URL bar. When I try to access APIs in AJAX request from other domains always this will return Unauthorized.

Here how to identify the user is authenticated or not from AJAX request?

API domain = ".apidomain.com"
Client domain = ".clientdomain.com"

API configuration:

services.AddAuthentication("oAuthSecurityScheme")
                .AddOAuth("login.microsoftonline.com",
                options =>
                {
                   ....
                   ....
                }).AddCookie(
                "oAuthSecurityScheme",
                options =>
                {
                options.LogoutPath = new PathString("/logout");
                options.LoginPath = new PathString("/api/v1/account/authorize");
                options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
                options.SlidingExpiration = true;
                options.Cookie.Name = "CustomerOAuthCookie";
                options.Events.OnRedirectToLogin = UnAuthorizedResponseAsync;
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.HttpOnly = false;
            });

Client Application:

$.ajax({
       url: "https://localhost:44332/api/gettickets/1",
       type: 'GET',
       success: function (result)
       {
          alert(result);
          console.log(result);
       }
});

Note: When I access the below API in the browser directly it will return the proper response https://localhost:44332/api/gettickets/1

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Madhan kumar D
  • 401
  • 2
  • 8
  • Checkout withcredentials: https://stackoverflow.com/questions/2054316/sending-credentials-with-cross-domain-posts – welrocken Mar 04 '21 at 12:53

2 Answers2

0

I usually prefer using tokens in order to send and save authorization data and suggest to you that. but if you still want to use cookie follow the below link way:

jquery ajax call not sending cookie

0

I am using axios to may ajax calls, and set "withCredentials" flag to true, so that in each request auth cookie is used.

import axios, { AxiosAdapter } from 'axios';
import { ApiBaseUrl } from '../config';

const http = axios.create({
  baseURL: ApiBaseUrl      
});    

http.interceptors.request.use(function (config) {
  config.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  config.withCredentials = true;
  return config;
});

export default http;

Below line informs the API server that it is ajax call

config.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Usage:

export class ProductsService implements IProductsService  {
  private _http: AxiosInstance;

  constructor(http: AxiosInstance) {
    this._http = http;
  }

  async GetProducts(id: string): Promise<Product[]> {
    let metadata = await this._http.get(
      "/products/" + id);
    return metadata.data as unknown as Product[];
  }
}

Note: config.withCredentials = true; needs to be used only after your login is done and auth cookie is set.

Santosh Karanam
  • 1,077
  • 11
  • 23