ASP.NET Core 3 API Ignores Authorize Attribute with Bearertoken - c#

I´m working on a ASP.NET Core Web API. I´m using the newest version 3.0.0-preview4.19216.2.
I have the problem, that my API-Controller ignores the Authorize-Attribute but on another controller the Attribute works fine.
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]
public class SuppliersController : ControllerBase
{
[HttpGet("GetAll")]
public IActionResult GetAll()
{
var companyId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value); // throws nullreference exception
return Ok();
}
}
But on another controller I have something similar but there the attribute works as expected
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class UsersController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var test = User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value;
}
}
In the user controller works everything fine.
I also tried it in the SupplierController without the
AuthenticationSchemes
but no different.
This is my AddAuthentication in the Startup.cs
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(userId);
if (user == null)
{
// return unauthorized if user no longer exists
context.Fail("Unauthorized");
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
Console.WriteLine(context);
return Task.CompletedTask;
},
OnMessageReceived = context =>
{
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
here is my complete startup.cs
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)
{
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
AuthenticationService.ConfigureSchoolProjectAuthentication(services, appSettingsSection);
DependencyInjectionService.Inject(services);
services.AddMvcCore()
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseAuthentication();
app.UseRouting();
app.UseEndpoints(routes =>
{
routes.MapControllers();
});
}
}
The strange thing is, when my SupplierController is called my authorization logic is not called (checked it with debugger) and when I call my UserController the logic is executed.
I think this is the reason why the claim is null. But why is the logic not called when the controller have a authorization attribute?
It´s seem like my authentication doesn't work entirely because I can access all my controller simply by using no authentication in Postman. What I´m doing wrong here?

Ok I found the anwser in this blog post ASP.NET Core updates in .NET Core 3.0 Preview 4
I have to change the order of my authentication registration from
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseAuthentication();
app.UseRouting();
app.UseEndpoints(routes =>
{
routes.MapControllers();
});
}
to
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
{
routes.MapControllers();
});
}
So this solve my problem.

Related

Use different aplication cookie or cookie options edit when login through api

I have a problem about api login with cookies, the goal is that before the user can call any api, the user must first call /api/Authentication/Login and then he can use the rest of the operations. However, when I call for example /api/Batch, instead of returning AccessDenied, I get the full html of the login page in the body of the response which is wrong in this case.
services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddHttpContextAccessor();
services.AddIdentity<User, Role>(o => {
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 8;
o.Password.RequireLowercase = true;
o.Password.RequireDigit = true;
o.Password.RequireUppercase = true;
}).AddEntityFrameworkStores<ScanLinkContext>().AddDefaultTokenProviders().AddRoles<Role>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/SignIn";
});
services
.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = ".AspNetCore.Cookies";
options.Cookie.HttpOnly = true;
options.LoginPath = "/Account/SignIn"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/SignOut"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/SignIn"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WEBAPI v1"));
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStatusCodePagesWithRedirects("/Errors/{0}");
app.UseRouting();
// Add authentication to request pipeline
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
I need to leave the original configuration, so that it is functional for the web and in the case of visiting a page to which the user has the right, it redirects him to the login page, but for the cookie I would need a different behavior as described above
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class BatchController : ControllerBase
{
private readonly ScanLinkContext _scanlinkContext;
public BatchController( ScanLinkContext scanLinkContext)
{
_scanlinkContext = scanLinkContext;
}
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[Route("Import")]
[HttpPost]
public async Task<StatusCodeResult> PostImport([FromBody] string xml)
{
return Ok();
}
[HttpPut("[action]/{batchName}")]
public async Task<StatusCodeResult> Tranform(string batchName, [FromBody] string json)
{
return Ok();
}
[HttpPut("[action]/{batchName}")]
public async Task<StatusCodeResult> Validate(string batchName, [FromBody] string json)
{
return Ok();
}
[HttpPut("[action]/{batchName}")]
public async Task<StatusCodeResult> Unlock(string batchName)
{
return Ok();
}
[HttpDelete("{batchName}")]
public async Task<StatusCodeResult> Delete(string batchName)
{
return Ok();
}
}
How should I adjust the configuration to achieve the goal?
You have to override the Events.OnRedriectLogin like this.
.ConfigureApplicationCookie(options =>
{
//other options...
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
}

Asp.Net Core API shuts down automatically when authorize is used

I have created an Asp.Net Web API for google authentication and here is my code in satrtup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddGoogle(options =>
{
options.ClientId = "591241482908-66qgk38nbf1un6xxxxxxxxx.apps.googleusercontent.com";
options.ClientSecret = "GOCSPX-xxxxxxxxxxxxx";
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
And there is Login Controller
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[HttpGet("{id}")]
[Authorize]
public ActionResult<string> Get(int id)
{
return Ok(this.User);
}
}
Now the code builds successfully, but whenever I run the web API the console and the application shuts down automatically. How Can I solve this?

API call: "Endpoint ... contains authorization metadata, but a middleware was not found that supports authorization."

I am currently working on creating a simple web application in angular using Auth0 to offload the authorization portion. Right now I am trying to connect the front end portion and the backend portion and I am having some trouble.
For some reason when I send a https request to the API it keeps giving me the following error in the chrome console.
So I went to use postman to try and access the api. I got past the CORS part error but instead het Endpoint .... contains authorization metadata, but a middleware was not found that supports authorization.
This is what my startup class looks like in my backend:
public class Startup
{
readonly string MyAllowSpecificOrigins = "localhost_origin";
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)
{
string domain = $"https://{Configuration["Auth0:Domain"]}/";
services.AddControllers();
// 1. Add Authentication Services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = Configuration["Auth0:ApiIdentifier"];
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
});
services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://localhost:4200").AllowAnyMethod().AllowAnyHeader();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Here is my test controller that I call the api on:
[Route("api")]
public class TestController : Controller
{
[HttpGet]
[Route("private")]
[Authorize]
public IActionResult Private()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated to see this."
});
}
}
I've read the documentation and followed the examples on auth0's sites for implementing this. I can't quite find where I went wrong.
Okay for the people that might run into a similar issue. It ended up being a problem of the order of things in the startup.cs file and making my localhost origin use http instead of https. I wasn't able to deduce this from the tutorial article because they ommitted a lot of code. I ended up having to download the sample project and compare line by line. This is the final startup.cs file that worked for me:
public class Startup
{
readonly string MyAllowSpecificOrigins = "localhost_origin";
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)
{
string domain = $"https://{Configuration["Auth0:Domain"]}/";
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
// 1. Add Authentication Services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = Configuration["Auth0:ApiIdentifier"];
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
});
services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

After clone of ASP.NET Core Web API project on other computer receiving MediatR error

In my computer application works fine, but other computers receiving next error after trying handle any request:
Error constructing handler for request of type MediatR.IRequestHandler`2[Application.User.Register+Command,Application.User.User]. Register your handlers with the container. See the samples in GitHub for examples
connection string
I register MediatR with following line in my Startup.cs:
services.AddMediatR(typeof(List.Handler).Assembly);
My Startup class:
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.AddDbContext<DataContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
});
});
services.AddMvc(opt =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
opt.Filters.Add(new AuthorizeFilter(policy));
})
.AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var builder = services.AddIdentityCore<AppUser>();
var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
identityBuilder.AddEntityFrameworkStores<DataContext>();
identityBuilder.AddSignInManager<SignInManager<AppUser>>();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateAudience = false,
ValidateIssuer = false
};
});
services.AddScoped<IJwtGenerator, JwtGenerator>();
services.AddScoped<IUserAccessor, UserAccessor>();
services.AddMediatR(typeof(List.Handler).Assembly);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
}
else
{
// app.UseHsts();
}
// app.UseHttpsRedirection();
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
}
}
Problem is that i cannot reproduce same issue on my computer.
Problem was on another level:
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));
It was problem with reading Configuration. After fixing it, all works as designed.

IdentityServer4 500 internal error, misssing EpochTimeExtensions when using authorize endpoint

I am creating a wep api backend for xamarin forms application with ASP.NET,
i'm using identityserver4 for authentication and authorization.
I want to use the authorization code workflow but i'm encountering a problem when i try to start the authorization/authentication request.
The error i receive is :
System.TypeLoadException: Could not load type 'IdentityModel.EpochTimeExtensions' from assembly 'IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=e7877f4675df049f'.
I haven't found a solution to this problem anywhere on the internet.
This is my Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddAutoMapper();
services.AddDbContext<SqlDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.GetResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddDeveloperSigningCredential();
services.AddControllers()
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World !");
});
});
}
}
This is my config.cs:
public class Config
{
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("Test", "TestService")
};
}
public static IEnumerable<IdentityResource> GetResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId()
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.Code,
RequireClientSecret = false,
RequireConsent = false,
AllowedScopes = new List<string>{ "Test" , "openid"},
AllowOfflineAccess = true,
RedirectUris = new List<String> {
"https://localhost:44392/account/test/"
}
}
};
}
}
And this is my request url :
https://localhost:44392/connect/authorize?client_id=client&response_type=code&redirect_uri=https://localhost:44392/account/test/&scope=Test openid&nonce=5&state=5
I hope someone here can help me.
Thanks in advance

Categories

Resources