Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use JWT for user authentication against Web Api 2 from angular SPA?

I'm trying to set up authentication from an AngularJS Single Page Application (SPA) to a Web Api built on OWIN. Here is what I have...

This is the login function (POST action on an AuthenticationController in API)

public HttpResponseMessage login(Credentials creds)
    {
        if (creds.Password == "password" && creds.Username.ToLower() == "username")
        {
            var user = new User { UserId = 101, Name = "John Doe", Role = "admin" };

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.Name), 
                    new Claim(ClaimTypes.Role, user.Role)
                }),

                AppliesToAddress = "http://localhost:/8080",
                TokenIssuerName = "myApi",

                SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TestApp.Api.Startup.GetBytes("ThisIsTopSecret")),
                    "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                    "http://www.w3.org/2001/04/xmlenc#sha256")
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return Request.CreateResponse<LoginResponse>(HttpStatusCode.Accepted, new LoginResponse { User = user, AuthToken = tokenString });
        }

        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

This is my OWIN startup config

public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "Default", 
            routeTemplate: "{controller}"
        );

        var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
        jsonSettings.Formatting = Formatting.Indented;
        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        app.UseWebApi(config);

        app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "http://localhost:8080" },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
            }
        });
    }

This is the angular code that I'm using to call a controller in the API that has the Authorized attribute.

$http({ method: 'GET', url: 'http://localhost:5000/Admin', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + Session.token }})
          .then(function (res) {
              return res.data;
          });

When I login I get the returned token as a string. I then store it in my client side Session. I then take it and put it in my header for subsequent requests.

When I try to call an "Authorized" action in the API i get a 401 response even though my token was passed in through the header of the request.

I'm new to JWT so I may be totally off base on my approach. Any advice would be great.

like image 785
Brett Feagans Avatar asked Sep 30 '22 07:09

Brett Feagans


1 Answers

I believe it is an order of operations thing. Move the app.UseJwt statement above the app.UseWebApi line.

    app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new[] { "http://localhost:8080" },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("myApp", TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
        }
    });

 app.UseWebApi(config);
like image 73
DavidEdwards Avatar answered Oct 11 '22 03:10

DavidEdwards