26
votes

I'm implementing a Web API 2 service architecture in my .NET web application. The client consuming the requests is pure javascript, no mvc/asp.net. I'm using OWIN to try to enable token authentication per this article OWIN Bearer Token Authentication with Web API Sample. I seem to be missing something with the authentication step after its authorized.

My login looks like:

    [HttpPost]
    [AllowAnonymous]
    [Route("api/account/login")]
    public HttpResponseMessage Login(LoginBindingModel login)
    {
        // todo: add auth
        if (login.UserName == "[email protected]" && login.Password == "a")
        {
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName));

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 

            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ObjectContent<object>(new  
                { 
                    UserName = login.UserName,
                    AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
                }, Configuration.Formatters.JsonFormatter)
            };
        }

        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }

It returns

{
   accessToken: "TsJW9rh1ZgU9CjVWZd_3a855Gmjy6vbkit4yQ8EcBNU1-pSzNA_-_iLuKP3Uw88rSUmjQ7HotkLc78ADh3UHA3o7zd2Ne2PZilG4t3KdldjjO41GEQubG2NsM3ZBHW7uZI8VMDSGEce8rYuqj1XQbZzVv90zjOs4nFngCHHeN3PowR6cDUd8yr3VBLdZnXOYjiiuCF3_XlHGgrxUogkBSQ",
   userName: "[email protected]"
}

Then I try to set the HTTP header Bearer on further requests in AngularJS like:

$http.defaults.headers.common.Bearer = response.accessToken;

to a API like:

    [HttpGet]
    [Route("api/account/profile")]
    [Authorize]
    public HttpResponseMessage Profile()
    {
        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(new
            {
                UserName = User.Identity.Name
            }, Configuration.Formatters.JsonFormatter)
        };
    }

but no matter what I do this service is 'unauthorized'. Am I missing something here?

2
The article link you provided shows a page stating 'This item is not yet published.'. I am very interested in enabling web api authorization with a bearer token. Can you please provide any resources or an updated link to the article you used? Thanks.likestoski
Hi, in your code I cannot see how you generated the access token! Could you please clarify it?s0nica
@s0nica .net does that automatically with owinamcdnl
Ok but I cannot see where and how you defined and assigned a value to the variable accessTokens0nica
@PeterStulinski - I wrote a gist that contains all the code I used for my implementation: gist.github.com/amcdnl/8239023amcdnl

2 Answers

27
votes

Resolved by setting header 'Authorization' with Bearer + token like:

$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
0
votes

You can configure it with your angular application module. So authorization token will be set as header for every http request.

var app = angular.module("app", ["ngRoute"]);
app.run(function ($http) {

     $http.defaults.headers.common.Authorization = 'Bearer ' + token.accessToken;

});