Mykhailo
Mykhailo

Reputation: 31

Passing token through Angular

I am trying to pass bearer token to my web api project from angular service

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization' :  'Bearer wYr2EBxSvQZlHgFjvWlznDJ4gNuw20r_pXBZKaCMAY3oROT5xqBiNutdjUdxWttmqdZmMy32-UlttNXosJcV7xlpVibawTKOxQRpvZK86K4AZ6ka_vzvrgPQcHXCClan0tzLmx38tLrPpLtX_y0M4nM7KzJ1NDoKqRJf6RtCIYWY0HUaDU8WE6qNMCrysOWLichS5zMBTSyNZVzSYTpIo4VxCqlAd_hmeljtyb8ypZ_0i-Xf7U4gNT6EcRMCAikNqPDF7ROy84qybDDgyx3CvcPC_JbvbnphrBuNVzRdiwu5MvN81gxNYiPY4Mp-HtJV2FZhnIwn_nQW3bFJVW4OZ5NW3IqLzoRI5HvllUnqfs0Jl4bNf8Pa5uSLDSG6rLAVps9QTWYlLtI-U4uRrOgespLPVlg7aYAt-vnSQkgMyJJI66wdPjuaXfjdIg0hZVTPihWt7bnyXB0mtvYa7QxXsW3KqIOt4OimTaYZRdt8-rQWvSzo2-Z8TY0q9W0crIVU'
      })
    };


 LikeImage(imageId: number): Observable<number> {      
    return this.http.post<number>('api/images/1/likes',httpOptions );
  }

My method in controller is following

    [Route("{imageId}/likes")]
    [Authorize]
    public IHttpActionResult LikeImage(int imageId)
    {
        if (imageId <= 0)
        {
            return BadRequest(message: "Invalid image id");
        }

        string userId = HttpContext.Current.User.Identity.GetUserId();
    (and etc.)
   }

The problem is that when I use Fiddler/Postman, all works and userId shows real user id, but when i am trying to pass same token from angular project GetUserId() returns null

Header when using angular

   POST /api/images/1/likes HTTP/1.1
    Host: localhost:56688
    Connection: keep-alive
    Content-Length: 52
    Accept: application/json, text/plain, */*
    Origin: http://localhost:4200
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
    Content-Type: application/json
    Referer: http://localhost:4200/images
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9

Header when using Postman/Fiddler

POST /api/images/2/likes HTTP/1.1
cache-control: no-cache
Postman-Token: 67afdaf3-d853-42a1-ad4b-f739d026a300
Authorization: Bearer (same access_token)
User-Agent: PostmanRuntime/7.2.0
Accept: */*
Host: localhost:56688
accept-encoding: gzip, deflate
content-length: 0
Connection: keep-alive

Upvotes: 0

Views: 735

Answers (1)

Nico
Nico

Reputation: 2021

your post method takes a body as the second parameter then it takes options (headers) as the third. See definition

However, I would encourage you to use an interceptor as with your approach you would have to adhoc add headers to each request which isn't too optimal!

Take a look here for a full explanation of how you could set up your own.

In essence you would do

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const modified = req.clone({setHeaders: {Authorization: 'Bearer mytokengoeshere'}});
        return next.handle(modified);
    }
}

And Inside your app.module

providers: [
{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
}]

Hope this helps.

Upvotes: 2

Related Questions