.NET CORE 2.1 JWT Bearer Authorization not invoked on request - Always returns 200 OK












1















I am doing a project where i have a separate front- and backend, and i want to protect my backend API with JWT bearer tokens.



When i send a get request from postman without any tokens attached, the API always return 200 OK. The debug console confirms that the Authorization middleware was not invoked. I do however get a HTTPS error??
Below is a link to an image of my console (new users can't have pictures directly in a question).



My console



I've looked at this guy's simple example of what i need exactly. His works no problem, and the console of his app shows authorization getting invoked, and i get 401 Unauthorized. When i use his approach nothing happens and i always get 200 OK.



In startup.cs i have both tried using services.AddMvc() as seen below, but also services.AddMvcCore().AddAuthorization(). Both resulted in Authorization not being invoked



Here is my startup.cs:



namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

var connection = Environment.GetEnvironmentVariable("DB");
services.AddDbContext<CoPassContext>(options => options.UseSqlServer(connection));
services.AddScoped<IRepository, Repository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseCors(c => c
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());

app.UseAuthentication();
app.UseMvc();
}
}


}



Here is a controller:



[Authorize]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private IDAO dao;

public CompanyController(IDAO db)
{
dao = db;
}

[Microsoft.AspNetCore.Mvc.HttpGet("search/{keyword}")]
public ActionResult<string> SearchCompanies(string keyword)
{
return JsonConvert.SerializeObject(dao.SearchCompanies(keyword));
}

// GET api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet("basic/{id}")]
public ActionResult<string> GetBasic(string id)
{
return dao.GetCompanyByRegNrBasic(id).ToString();
}









share|improve this question




















  • 1





    The order of your middleware is important - try adding the authentication earlier in the configuration

    – ste-fu
    Oct 10 '18 at 14:33











  • Tried this without any luck

    – Alexander
    Oct 11 '18 at 6:50











  • I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

    – Alexander
    Oct 11 '18 at 9:26
















1















I am doing a project where i have a separate front- and backend, and i want to protect my backend API with JWT bearer tokens.



When i send a get request from postman without any tokens attached, the API always return 200 OK. The debug console confirms that the Authorization middleware was not invoked. I do however get a HTTPS error??
Below is a link to an image of my console (new users can't have pictures directly in a question).



My console



I've looked at this guy's simple example of what i need exactly. His works no problem, and the console of his app shows authorization getting invoked, and i get 401 Unauthorized. When i use his approach nothing happens and i always get 200 OK.



In startup.cs i have both tried using services.AddMvc() as seen below, but also services.AddMvcCore().AddAuthorization(). Both resulted in Authorization not being invoked



Here is my startup.cs:



namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

var connection = Environment.GetEnvironmentVariable("DB");
services.AddDbContext<CoPassContext>(options => options.UseSqlServer(connection));
services.AddScoped<IRepository, Repository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseCors(c => c
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());

app.UseAuthentication();
app.UseMvc();
}
}


}



Here is a controller:



[Authorize]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private IDAO dao;

public CompanyController(IDAO db)
{
dao = db;
}

[Microsoft.AspNetCore.Mvc.HttpGet("search/{keyword}")]
public ActionResult<string> SearchCompanies(string keyword)
{
return JsonConvert.SerializeObject(dao.SearchCompanies(keyword));
}

// GET api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet("basic/{id}")]
public ActionResult<string> GetBasic(string id)
{
return dao.GetCompanyByRegNrBasic(id).ToString();
}









share|improve this question




















  • 1





    The order of your middleware is important - try adding the authentication earlier in the configuration

    – ste-fu
    Oct 10 '18 at 14:33











  • Tried this without any luck

    – Alexander
    Oct 11 '18 at 6:50











  • I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

    – Alexander
    Oct 11 '18 at 9:26














1












1








1








I am doing a project where i have a separate front- and backend, and i want to protect my backend API with JWT bearer tokens.



When i send a get request from postman without any tokens attached, the API always return 200 OK. The debug console confirms that the Authorization middleware was not invoked. I do however get a HTTPS error??
Below is a link to an image of my console (new users can't have pictures directly in a question).



My console



I've looked at this guy's simple example of what i need exactly. His works no problem, and the console of his app shows authorization getting invoked, and i get 401 Unauthorized. When i use his approach nothing happens and i always get 200 OK.



In startup.cs i have both tried using services.AddMvc() as seen below, but also services.AddMvcCore().AddAuthorization(). Both resulted in Authorization not being invoked



Here is my startup.cs:



namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

var connection = Environment.GetEnvironmentVariable("DB");
services.AddDbContext<CoPassContext>(options => options.UseSqlServer(connection));
services.AddScoped<IRepository, Repository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseCors(c => c
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());

app.UseAuthentication();
app.UseMvc();
}
}


}



Here is a controller:



[Authorize]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private IDAO dao;

public CompanyController(IDAO db)
{
dao = db;
}

[Microsoft.AspNetCore.Mvc.HttpGet("search/{keyword}")]
public ActionResult<string> SearchCompanies(string keyword)
{
return JsonConvert.SerializeObject(dao.SearchCompanies(keyword));
}

// GET api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet("basic/{id}")]
public ActionResult<string> GetBasic(string id)
{
return dao.GetCompanyByRegNrBasic(id).ToString();
}









share|improve this question
















I am doing a project where i have a separate front- and backend, and i want to protect my backend API with JWT bearer tokens.



When i send a get request from postman without any tokens attached, the API always return 200 OK. The debug console confirms that the Authorization middleware was not invoked. I do however get a HTTPS error??
Below is a link to an image of my console (new users can't have pictures directly in a question).



My console



I've looked at this guy's simple example of what i need exactly. His works no problem, and the console of his app shows authorization getting invoked, and i get 401 Unauthorized. When i use his approach nothing happens and i always get 200 OK.



In startup.cs i have both tried using services.AddMvc() as seen below, but also services.AddMvcCore().AddAuthorization(). Both resulted in Authorization not being invoked



Here is my startup.cs:



namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

var connection = Environment.GetEnvironmentVariable("DB");
services.AddDbContext<CoPassContext>(options => options.UseSqlServer(connection));
services.AddScoped<IRepository, Repository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseCors(c => c
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());

app.UseAuthentication();
app.UseMvc();
}
}


}



Here is a controller:



[Authorize]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private IDAO dao;

public CompanyController(IDAO db)
{
dao = db;
}

[Microsoft.AspNetCore.Mvc.HttpGet("search/{keyword}")]
public ActionResult<string> SearchCompanies(string keyword)
{
return JsonConvert.SerializeObject(dao.SearchCompanies(keyword));
}

// GET api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet("basic/{id}")]
public ActionResult<string> GetBasic(string id)
{
return dao.GetCompanyByRegNrBasic(id).ToString();
}






c# jwt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 10 '18 at 13:52







Alexander

















asked Oct 10 '18 at 13:45









AlexanderAlexander

62




62








  • 1





    The order of your middleware is important - try adding the authentication earlier in the configuration

    – ste-fu
    Oct 10 '18 at 14:33











  • Tried this without any luck

    – Alexander
    Oct 11 '18 at 6:50











  • I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

    – Alexander
    Oct 11 '18 at 9:26














  • 1





    The order of your middleware is important - try adding the authentication earlier in the configuration

    – ste-fu
    Oct 10 '18 at 14:33











  • Tried this without any luck

    – Alexander
    Oct 11 '18 at 6:50











  • I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

    – Alexander
    Oct 11 '18 at 9:26








1




1





The order of your middleware is important - try adding the authentication earlier in the configuration

– ste-fu
Oct 10 '18 at 14:33





The order of your middleware is important - try adding the authentication earlier in the configuration

– ste-fu
Oct 10 '18 at 14:33













Tried this without any luck

– Alexander
Oct 11 '18 at 6:50





Tried this without any luck

– Alexander
Oct 11 '18 at 6:50













I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

– Alexander
Oct 11 '18 at 9:26





I found a (bad) solution. I made a new project, and copied everything from the old one to the new one. Authorization works now! I have no idea what was wrong, maybe some of my imports were wrong or something...?

– Alexander
Oct 11 '18 at 9:26












1 Answer
1






active

oldest

votes


















0














It looks like you forgot to add the authorization.



Like @ste-fu said, try add this below the services.AddAuthentication(..);



services.AddAuthorization();





share|improve this answer
























  • I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

    – Alexander
    Oct 10 '18 at 19:28













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52741709%2fnet-core-2-1-jwt-bearer-authorization-not-invoked-on-request-always-returns-2%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














It looks like you forgot to add the authorization.



Like @ste-fu said, try add this below the services.AddAuthentication(..);



services.AddAuthorization();





share|improve this answer
























  • I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

    – Alexander
    Oct 10 '18 at 19:28


















0














It looks like you forgot to add the authorization.



Like @ste-fu said, try add this below the services.AddAuthentication(..);



services.AddAuthorization();





share|improve this answer
























  • I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

    – Alexander
    Oct 10 '18 at 19:28
















0












0








0







It looks like you forgot to add the authorization.



Like @ste-fu said, try add this below the services.AddAuthentication(..);



services.AddAuthorization();





share|improve this answer













It looks like you forgot to add the authorization.



Like @ste-fu said, try add this below the services.AddAuthentication(..);



services.AddAuthorization();






share|improve this answer












share|improve this answer



share|improve this answer










answered Oct 10 '18 at 15:02









Deivid CarvalhoDeivid Carvalho

1068




1068













  • I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

    – Alexander
    Oct 10 '18 at 19:28





















  • I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

    – Alexander
    Oct 10 '18 at 19:28



















I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

– Alexander
Oct 10 '18 at 19:28







I tried this but it didn't work. I also tried placing AddAuthentication(..) and AddAuthorization at the top - also no success

– Alexander
Oct 10 '18 at 19:28




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52741709%2fnet-core-2-1-jwt-bearer-authorization-not-invoked-on-request-always-returns-2%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Create new schema in PostgreSQL using DBeaver

Deepest pit of an array with Javascript: test on Codility

Costa Masnaga