techie_coder
techie_coder

Reputation: 1

Not able to read cookies in Angular from API response (Spring Boot Service) - Cannot read properties of null (reading 'headers')

Service Code

public ResponseEntity<String> getSessionCookie() {
    logger.info("Get Cookies");
    var cookie1 = ResponseCookie.from("ASP.NET_SessionId_Wx", appConfig.getSessionId()).httpOnly(false).path("/").secure(false).build();
        var cookie2 = ResponseCookie.from("WX-XSRF-TOKEN", appConfig.getToken()).httpOnly(false).path("/").build();

    return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie1.toString())
                .header(HttpHeaders.SET_COOKIE, cookie2.toString()).build();
    }

Angular Code

Service

public getSession(): Observable<any> {  
     return this.http.get<any>('//example.com/getSessionCookie/', {withCredentials: true});
  }

Component

    this.ds.getSession().subscribe((res) => {
        console.log('Get Session Header: ', res.headers);
    })
  }

Able to view the cookies in Postman and Chrome Dev Tools (Network tab - Response Headers)

Added CORS config to SprinBoot App

public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
        public void addCorsMappings(CorsRegistry registry) {              
registry.addMapping("/**").allowedOriginPatterns("*").allowedHeaders("*").allowCredentials(true)
                    .allowedMethods("GET", "POST", "PUT", "DELETE");
        }
}

Upvotes: 0

Views: 231

Answers (1)

techie_coder
techie_coder

Reputation: 1

I figured it out.

The issue was with the 'Set-Cookie'. Angular is unable to read the 'Set-Cookie' header. Changed the header key to some other name and added the same in exposedHeaders as well.

Worked like a Charm:).

Thanks.

Upvotes: 0

Related Questions