.NET CORE 2.1 JWT Bearer Authorization not invoked on request - Always returns 200 OK
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
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
add a comment |
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
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
add a comment |
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
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
c# jwt
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
It looks like you forgot to add the authorization.
Like @ste-fu said, try add this below the services.AddAuthentication(..);
services.AddAuthorization();
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
add a comment |
With Mvc Core 2.2 instead of using services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
It looks like you forgot to add the authorization.
Like @ste-fu said, try add this below the services.AddAuthentication(..);
services.AddAuthorization();
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
add a comment |
It looks like you forgot to add the authorization.
Like @ste-fu said, try add this below the services.AddAuthentication(..);
services.AddAuthorization();
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
add a comment |
It looks like you forgot to add the authorization.
Like @ste-fu said, try add this below the services.AddAuthentication(..);
services.AddAuthorization();
It looks like you forgot to add the authorization.
Like @ste-fu said, try add this below the services.AddAuthentication(..);
services.AddAuthorization();
answered Oct 10 '18 at 15:02
Deivid CarvalhoDeivid Carvalho
1118
1118
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
add a comment |
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
add a comment |
With Mvc Core 2.2 instead of using services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line.
add a comment |
With Mvc Core 2.2 instead of using services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line.
add a comment |
With Mvc Core 2.2 instead of using services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line.
With Mvc Core 2.2 instead of using services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line.
answered Feb 11 at 15:06
AvrohomAvrohom
245216
245216
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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