angularazureazure-web-app-servicebackendsetcookie

Conection and send cookie between multiple AppService - Azure


I have 2 AppService, one for my django backend and another for my angular frontend. Each appService has its domain. On the login endpoint, the backend must generate and set a cookie with a jwt in the frontend context and domain to enable navigation. From what I understand, since there are 2 app services with 2 different domains, the creation of the cookie in the backend corresponds to a different domain than the frontend and therefore this is rejected by the browser, rejecting the cookie. (Even configuring the httpOnly, Secure, Domain and path attribute in the backend). Is it possible to configure that both appServices share the same domain, so that the cookie persists in the context of the frontEnd?

enter image description here

I tried setting the domain attribute in the backend setCookie to the frontend domain but the browser continues to reject it.


Solution

  • Is it possible to configure that both appServices share the same domain

    Yes, we can configure it by adding custom domain taken an (e.g., backend.example.com or frontend.example.com).

    enter image description here

    enter image description here

    Django:

    from django.http import JsonResponse
    
    def login(request):
        # Perform login logic
        # Assuming jwt_token is the JWT token you want to set
        response = JsonResponse({'message': 'Login Successful'})
        response.set_cookie('jwt_token', 'your_jwt_token', domain='frontend.example.com')
        return response
    

    Angular:

    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthService {
    
      private apiUrl = 'https://backend.example.com';
    
      constructor(private http: HttpClient) { }
    
      login(credentials: any): Observable<any> {
        return this.http.post(`${this.apiUrl}/login/`, credentials, { withCredentials: true });
      }
    }
    

    Include the withCredentials: true option in your HTTP requests.

    Configure CORS to the Django Backend, In the settings Django backend App Service, you can find the CORS settings section. Add the domain https://frontend.example.com to the list of allowed origins

    As per the above configuring Headers-set_cookies with both the applications the cookies persist in the context of the one domain only.

    enter image description here