简体   繁体   中英

How to retrieve cookie on the client side sent by c# server Response.Cookies.Append method

Can I retrieve on the angular client side cookie sent by the c# server like in the code below (and how to do that if possible).

private void setTokenCookie(string token)
{
    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Expires = DateTime.UtcNow.AddDays(7)
    };
    Response.Cookies.Append("refreshToken", token, cookieOptions);
}

I am going to attempt to answer my own question after two days of experiments and investigation.

Sending cookie to c# server and back from c# server to angular client is a few steps process:

First send a message (post/get etc) from client to server - with the withCredentials: true :

login(email: string, password: string) {
        return this.http.post<any>(`${baseUrl}/authenticate`, { email, password }, { withCredentials: true } )
            .pipe(map(account => {
                const body = account.body;
                this.accountSubject.next(account.body);
                const expires = new Date(Date.now() + 7*24*60*60*1000).toUTCString();

                const cookie = document.cookie; <-- for debugging purpose only
                //document.cookie = `refreshToken=${body.refreshToken}; expires=${expires}; path=/`;
                this.startRefreshTokenTimer();
                return account;
            }));
}

Then send from c# server back to the client the cookie added to the Response object like below (this sets the cookie on the client side):

var cookieOptions = new CookieOptions
{
    HttpOnly = false, // false for debug purpose to be able to see it on the client side
    Expires = DateTime.UtcNow.AddDays(7),
};
Response.Cookies.Append("refreshToken", token, cookieOptions);

After that the cookie is send by the angular client automatically to the c# server every time we execute another post/get etc command

Can some expert please confirm that this is what is happening with cookies handling between server and client?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM