0

I have an ASP.NET Core 3.1 API that uses JWT authentication, the API is intended to send resources to an Angular project. Some of the methods are protected by authentication with user log in. This works in Visual Studio debugging. But on IIS I only get 401 errors on any of these methods, even though the api returns the correct token upon logging in.

I don't know what I'm doing wrong, I actually have no idea what I'm doing at this point. Any help with the API and IIS will be very much appreciated.

StartUp.cs

services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer = "https://localhost:8080",
                    ValidAudience = "https://localhost:8080",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySecretKey"))
                };
            });

appSettings.json

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false
  }

UserController.cs

[HttpPost("login")]
        public IActionResult Login([FromBody]User input)
        {
            if (input == null)
            {
                return BadRequest("Invalid client request");
            }

            var user = _context.Users.FirstOrDefault(ol => ol.Email == input.Email && ol.Password == input.Password);

            if (user != null)
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySecretKey"));
                var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.Role, user.Admin ? "Admin" : "NormalUser")
                };

                var tokenOptions = new JwtSecurityToken(
                    issuer: "https://localhost:8080",
                    audience: "https://localhost:8080",
                    claims: claims,
                    expires: DateTime.Now.AddHours(2),
                    signingCredentials: signingCredentials
                );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);

                return Ok(new { Token = tokenString });
            }
            else
            {
                return Ok(new { Token = "Unauthorized" });
            }
        }

Other Controller Example Method

[Authorize(Roles = "Admin")]
        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                doStuff();
            }
            catch (Exception e)
            {
                return BadRequest(e);
            }

            return Ok();
        }
  • The problem could be in these lines ValidIssuer = "https://localhost:8080", ValidAudience = "https://localhost:8080" I don't know which address do you use for IIS hosting, but presume that it is not localhost:8080. – Volodymyr Puzdriak Jun 22 '20 at 23:52
  • So that I'm 100% confident that it is correct, as my Angular applocationruns on 8081 and the API runs on 8080, furthermore, the Angular application does make successful api calls, but only the calls that do not need authorization – Johannes Karsten Jun 22 '20 at 23:55
  • What happens if you toggle the windowsAuthentication property in iisSettings to false? If you are using token authentication, you shouldn't need the windows Authentication feature, unless you really mean to use both. – Bruno Farias Jun 23 '20 at 01:51
  • If you published your application to IIS, you should firstly check the IIS management console authentication feature to make sure you have enable the anonymousAuthentication and disable the windowsAuthentication. – Brando Zhang Jun 23 '20 at 02:26

1 Answers1

0

My friend found my problem! The token was never added to the auth header for the requests. All I did was add the token to every request using a HTTP Interceptor. The real question is how did it work in debugging without the interceptor?

I guess what we can learn from this is to check your headers first before running to StackOverflow.

I used Martin Adámek's answer on this question.