Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSESSIONID value and create Cookie in AngularJS

I'm using a Web RestFUL API from my client in AngularJS.

app.controller('LoginController', [
    '$http',
    '$cookies', 

    function($http, $cookies) {
      this.credentials = {};

      this.http = $http;

      this.login = function() {
        console.log(this.credentials);

        var authdata = btoa(
            this.credentials.username +
            ':' +
            this.credentials.password
        );

        $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;

        console.log($http);

        var res = $http.post("http://API_NAME/library");

        res.success(function(data, status, header){
            alert('Successfull func');

            console.log($cookies.get('JSESSIONID'));
        });

        res.error(function(data, status, headers, config) {
            console.log('Error Log');
        });
     };
   },
]);

Then, i have this Http headers Response

Set-Cookie:JSESSIONID=azekazEXAMPLErezrzez; Path=/; HttpOnly

I'm using ngCookies to get the JSESSIONID value and then create it manually in my browser, but i can't access it.

I already saw all the posts about this in StackOverflow, but they are deprecated or completely unclear.

Thanks for your interest and help.

like image 693
Louis Lecocq Avatar asked Oct 07 '15 11:10

Louis Lecocq


People also ask

How to create cookies in AngularJS?

Angular has inbuilt directives named as ngCookies. Writing Cookies: The WriteCookie function of the controller gets called When the Write Cookie Button is clicked. The WriteCookie function saves the input box value as cookies, using the $cookieStore service of the ngCookies module.

What is used to read or write a cookie by AngularJS?

AngularJS uses ngCookies module and $cookieStoreservice to carry out the various functions of reading, writing and removing Cookies. The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.

How do I get data from cookies in angular 6?

You just have to split the string if you want to get the value by the semicolon first and then by the = . If you'd like to add a value to it just append a semicolon to the end, and then print your cookie in a key=value format.


1 Answers

You can't get HttpOnly cookies with JavaScript. That is the whole purpose of the HttpOnly flag.

That said, you shouldn't need to. The cookie should be sent automatically with any request to the same server. If you are dealing with cross-origin XHR requests, set your_XHR_instance.withCredentials to true to include cookies.

like image 160
Quentin Avatar answered Oct 13 '22 00:10

Quentin