Search code examples
oauth-2.0asp.net-core-mvcjwtasp.net-core-webapiasp.net-core-2.1

JWT Same Application is the Auth Server and the Application Server


Hi experts I have recently explored a lot on OAuth and how JWT works. Essentially there should be an AuthServer that issues a token and there should be a ServiceAPI(Application Server) that uses the token for a client!!. I also understand a token is made up of 3-parts, the header, payload and signature...

Now what if I want to build an API that does both ...Authenticates and issues JWT tokens - and then provide the service afterwards..It Sounds like Basic Authentication with tokens!!

I am also unsure if the code I have written reflects this concept (that token issuer is the same as ServiceAPI). I am building a .net core 2.1 Web API following this article.

In the Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = "https://localhost:44387/";
            options.Audience = "JWT:Issuer";
            options.TokenValidationParameters.ValidateLifetime = true;
            options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(5);
            options.RequireHttpsMetadata = false;
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("GuidelineReader", p => {
                p.RequireClaim("[url]", "GuidelineReader");
            });
        });
    }

I have also added a LoginController that generates the token and returns it...

[AllowAnonymous]
    [HttpPost]
    public IActionResult Login([FromBody]Application login)
    {
        IActionResult response = Unauthorized();
        var user = AuthenticateUser(login);

        if (user != null)
        {
            var tokenString = GenerateJSONWebToken(user);
            response = Ok(new { token = tokenString });
        }

        return response;
    }

private string GenerateJSONWebToken(Application appInfo)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          null,
          expires: DateTime.Now.AddMinutes(120),
          signingCredentials: credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

What is the difference in the following

  • options.Authority
  • options.Audience (I am thinking it is the application that sends https request)
  • options.Issuer

Solution

  • options.Authority

    Authority is the address of the token-issuing authentication server. In your scenario the web api issue the token , so the Authority will be the url of web api .

    options.Audience (I am thinking it is the application that sends https request)

    Audience represents the intended recipient of the incoming token or the resource that the token grants access to. In your scenario ,the web api is the protected resource which client will access with JWT token , web api will validate the token to check the claims/signature . So web api name/URL should be the Audience

    options.Issuer

    Issuer Identifies the security token service (STS) that constructs and returns the token . In your scenario , the web api validates the user credential and return token. So web api name/URL is the Issuer