Search code examples
c#asp.netasp.net-web-apiasp.net-identity-2bearer-token

Why is my ASP.NET Web API with Identity 2 not granting me access to protected resources?


I have a Web API using Identity 2. It seems to authenticate me fine, and the /Token endpoint returns what I deserialize to an AuthTicket instance, with contents much like:

AccessToken: "averylongtoken"
Expires: {2016/12/12 8:19:22 AM}
ExpiresIn: 1209599
Issued: {2016/11/28 8:19:22 AM}
TokenType: "bearer"
Username: "myusername"

Then, when I send a request like:

var response = await Client.GetAsync("api/appt/3/true", cancellationToken);

and Client.DefaultRequestHeaders.Authorization looks like:

Bearer theSameVeryLongToken

I still get a 401 - Not authorized. What could be wrong here? Could it be that the Web API is somehow not receiving or properly decrypting the bearer token? When I set a break-point in the API, and examine the User property in the controller action, all its properties are null or default, but it has one ClaimsIdentity, whose properties are also all null or default, and its Claims collection is empty.

Do I manually have to set all claims vs. only my custom ones? I would have thought ApplicationOAuthProvider.GrantResourceOwnerCredentials would at least add a claim such as the user name or id.


Solution

  • I reviewed all code again, somehow had lost the line that added the auth token to the request headers. Inspecting these headers before sending the request easily confirmed this, and it was easily fixed.