How to Authorize Controller .NET Core API - asp.net-core

I'm able to generate tokens succesfully when user login the app.But after I added [Authorize] on my controller,that token comes from header cannot pass the authorization.On Postman returns Unauthorized even though sending up-to date token in header to controller.Before added [Authorize] that worked very well
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)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers().AddNewtonsoftJson(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.AddAutoMapper(typeof(AppointmentRepository).Assembly);
services.AddScoped<IHospitalRepository, HospitalRepository>();
services.AddScoped<IAppointmentRepository, AppointmentRepository>();
services.AddScoped<IPatientRepository, PatientRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
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.UseAuthorization();
app.UseCors(x => x.WithOrigins().AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
login Method in controller
[HttpPost("login")]
public async Task<IActionResult> Login(PatientLoginDto patientLoginDto)
{
//if user exists or not
var patientFromRepo = await _repo.Login(patientLoginDto.IdentityNumber, patientLoginDto.Password);
if (patientFromRepo == null)
{ return Unauthorized(); }
var claims = new[]
{
//Token has two claim username and id
new Claim(ClaimTypes.NameIdentifier,patientFromRepo.Id.ToString()),
new Claim(ClaimTypes.NameIdentifier,patientFromRepo.Name)
};
//key generated
var key = new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
//passing claims
Subject = new ClaimsIdentity(claims),
//expiry date in hours
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
//storing token here(based on token descriptor object)
var token = tokenHandler.CreateToken(tokenDescriptor);
var patient = _mapper.Map<PatientLoggedinDto>(patientFromRepo);
return Ok(new
{
//as response send back to the client
token = tokenHandler.WriteToken(token),
patient
});
}
}

You need register the AuthenticationMiddleware before app.UseAuthorization();:
app.UseRouting();
app.UseAuthentication(); // add this line. NOTE The order is important.
app.UseAuthorization();
// ... other middlewares

Related

ASP.NET Core Web Api - Problem with using session

I am developing an asp.net core web api and I want to store a token that will be sent to my endpoints in order for a user to authenticate. For that I have some requirements which force me to implement an own authentication method. I inherit from AuthenticationHandler and implement the HandleAuthenticateAsync method:
public AuthenticateHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IHttpContextAccessor httpContextAccessor)
: base(options, logger, encoder, clock)
{
AuthenticateHandlerHelperFunctions = new AuthenticateHandlerHelperFunctions();
_checkAccessTokenModel = new CheckAccessTokenModel();
session = httpContextAccessor.HttpContext.Session;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//before this: check header and get authorization informations
string submittedToken = authorizationheader.Substring("bearer".Length).Trim();
try
{
if (string.IsNullOrEmpty(session.GetString("Token")))
{
_checkAccessTokenModel = await AuthenticateHandlerHelperFunctions.CheckAccessToken(submittedToken);
if(_checkAccessTokenModel.Active == false)
{
_failReason = "Token not valid anymore, request another one!";
return AuthenticateResult.Fail("Token not valid anymore, request another one!");
}
session.SetString("Token", submittedToken);
}
}
catch
{
return AuthenticateResult.Fail("Invalid Authorization Header");
}
var claims = new[] {
new Claim(ClaimTypes.Name, _checkAccessTokenModel.Exp.ToString()),
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
The goal is to use the session to save the token and not execute the CheckAccessToken method for every request. I will get frequent data on the endpoints that are configured with [Authorize] so I want to save computing time. I looked this up and most of the errors where problems with the startup where the app.UseSession() was not set correctly etc. but not in my case I believe. Here is my Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "DigVPapi", Version = "v1" });
});
services.AddDbContextFactory<AntragDBNoInheritanceContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, AuthenticateHandler>("BasicAuthentication", null);
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = System.TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddHttpContextAccessor();
services.AddSingleton<IJWTManagerRepository, JWTManagerRepository>();
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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DigVPapi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
If this is not possible. What could I do instead to save the token in some different way? Of course I could save the token in the database but this would only move the problem to a database query tha twould be made every time. The error that I get when trying to authenticate is following
System.InvalidOperationException: 'Session has not been configured for this application or request.'

How to delete cookie on browser close

I'm implementing asp.net core project and I authenticate the user via ldap by using Novell.Directory.Ldap.NETStandard. Now my problem is How can I delete cookie after the user close the browser. I want whenever the user close the browser and opens the system again, he confronts with login page. here below is what I've tried in startup for setting cookie:
services.AddScoped<Ldap.IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.LoginPath = "/Account/Login";
options.SlidingExpiration = true;
});
And here is my AccountController:
public class AccountController : Controller {
private readonly Ldap.IAuthenticationService _authenticationService;
private readonly IHttpContextAccessor _httpContext;
public AccountController(Ldap.IAuthenticationService authenticationService,IHttpContextAccessor context)
{
_httpContext = context;
_authenticationService = authenticationService;
}
public IActionResult Login()
{
return View();
}
[HttpPost]
// [ChildActionOnly]
public async Task<IActionResult> Login(LoginModel model)
{
LdapEntry result1 = null;
var result = _authenticationService.ValidateUser1("mm.fr", model.UserName, model.Password);
if (result.Equals(true))
{
result1 = _authenticationService.GetLdapUserDetail("mm.fr", model.UserName, model.Password);
ViewBag.Username = result1.GetAttribute("CN").StringValue;
Index(result1.GetAttribute("CN").StringValue);
if (result != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
}
else
{
this.TempData["ErrorMessage"] = "Password is incorrect";
}
return RedirectToAction(nameof(MainDashboardController.Index), "MainDashboard");
}
public IActionResult Index(string str)
{
_httpContext.HttpContext.Session.SetString("mystr", str);
return View();
}
}
Here below is what I wrote in Startup:
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.AddControllersWithViews();
services.AddDbContext<CSDDashboardContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));
//Notice this is NOT the same class... Assuming this is a valid DBContext. You need to add this class as well.
//services.AddDbContext<CSSDDashboardContext>(options =>
// options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));
//*---------------------------New Active Directory--------------------------------
services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.LoginPath = "/Account/Login";
options.SlidingExpiration = true;
});
services.AddSession();
services.AddSingleton<MySharedDataViewComponent>();
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
$(window).unload(function() {
deleteCookie('Your cookie to delete name');
});

Error trying to get authenticate with google in ASP.NET Core 3.1 No authentication handler is registered

The Error
This is my startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Demand authentication in the whole application
services.AddControllersWithViews(o => o.Filters.Add(new AuthorizeFilter()));
services.AddScoped<IConferenceRepository, ConferenceRepository>();
services.AddScoped<IProposalRepository, ProposalRepository>();
services.AddScoped<IAttendeeRepository, AttendeeRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddDbContext<ConfArchDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly =>
assembly.MigrationsAssembly(typeof(ConfArchDbContext).Assembly.FullName)));
services
.AddAuthentication(options =>
{
options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =
GoogleDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.IsEssential = true;
//options.Cookie.SameSite = SameSiteMode.None;
})
.AddGoogle(options =>
{
options.SignInScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.ClientId =
Configuration["Authentication:Google:ClientId"];
options.ClientSecret =
Configuration["Authentication:Google:ClientSecret"];
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
//app.UseIdentity();
// app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Conference}/{action=Index}/{id?}");
});
}
}
this is my controller, the error is thrown in the line: var result = await HttpContext.AuthenticateAsync(
public class AccountController : Controller
{
private readonly IUserRepository userRepository;
public AccountController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
// This method must be anonymous to allow access to not logged users
[AllowAnonymous]
public IActionResult Login(string returnUrl = "/")
{
return View(new LoginModel { ReturnUrl = returnUrl });
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginModel model)
{
// Looking for user in local repository in the class userrepository
var user = userRepository.GetByUsernameAndPassword(model.Username, model.Password);
if (user == null)
return Unauthorized();
// Data of the user, claims class is used to represent the data user
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
new Claim("FavoriteColor", user.FavoriteColor)
};
// Object to save in Identity object type ClaimsIdentity
var identity = new ClaimsIdentity(claims,
CookieAuthenticationDefaults.AuthenticationScheme);
// Create claims principal object with the Identity
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties { IsPersistent =
model.RememberLogin,
ExpiresUtc= DateTime.UtcNow.AddMinutes(10)
});
return LocalRedirect(model.ReturnUrl);
}
[AllowAnonymous]
public IActionResult LoginWithGoogle(string returnUrl = "/")
{
var props = new AuthenticationProperties
{
RedirectUri = Url.Action("GoogleLoginCallback"),
Items =
{
{ "returnUrl", returnUrl }
}
};
return Challenge(props, GoogleDefaults.AuthenticationScheme);
}
[AllowAnonymous]
public async Task<IActionResult> GoogleLoginCallback()
{
// read google identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(
ExternalAuthenticationDefaults.AuthenticationScheme);
var externalClaims = result.Principal.Claims.ToList();
var subjectIdClaim = externalClaims.FirstOrDefault(
x => x.Type == ClaimTypes.NameIdentifier);
var subjectValue = subjectIdClaim.Value;
var user = userRepository.GetByGoogleId(subjectValue);
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
new Claim("FavoriteColor", user.FavoriteColor)
};
var identity = new ClaimsIdentity(claims,
CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
// delete temporary cookie used during google authentication
await HttpContext.SignOutAsync(
ExternalAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, principal);
return LocalRedirect(result.Properties.Items["returnUrl"]);
}
// Action to logout
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
}
I figure out the answer, the in the configure services code should be so:
// Demand authentication in the whole application
services.AddControllersWithViews(o => o.Filters.Add(new
AuthorizeFilter()));
services.AddScoped<IConferenceRepository, ConferenceRepository>();
services.AddScoped<IProposalRepository, ProposalRepository>();
services.AddScoped<IAttendeeRepository, AttendeeRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddDbContext<ConfArchDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
assembly =>
assembly.MigrationsAssembly(typeof(ConfArchDbContext).Assembly.FullName)));
services.AddAuthentication(o => {
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddCookie(ExternalAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(o =>
{ // ClienteId and Secret to authenticate the user from Google
o.SignInScheme =
ExternalAuthenticationDefaults.AuthenticationScheme;
o.ClientId = Configuration["Authentication:Google:ClientId"];
o.ClientSecret =
Configuration["Authentication:Google:ClientSecret"];
});

cant access JWT token because of CORS using .NetCore

I have a very strange issue on the back end side of my application,here is my Startup:
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
string securityKey = "My_First_Key_generated_by_myself";
var semetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
services.AddCors(options =>
{
options.AddPolicy(
"EnableCORS",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials().Build());
});
services.AddAuthentication().AddJwtBearer(
options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "morteza",
ValidAudience = "pass",
IssuerSigningKey = semetricSecurityKey
};
}
);
}
// 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();
}
app.UseAuthentication();
//app.UseHttpsRedirection();
app.UseCors("EnableCORS");
app.UseMvc();
}
My Athentication Controller to generate Token:
[HttpPost("token")]
// [Authorize]
public ActionResult GetToken(string username)
{
// return Ok("hi Morteza");
if (username == "morteza") {
string securityKey = "My_First_Key_generated_by_myself";
var semetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
var signIncredentials = new SigningCredentials(semetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
issuer: "morteza",
audience: "pass",
expires: DateTime.Now.AddHours(1),
claims: claims,
signingCredentials: signIncredentials);
return Ok(new JwtSecurityTokenHandler().WriteToken(token));
}
else
{
return null;
}
}
I have no idea why I get Access to XMLHttpRequest at 'https://localhost:44361/api/Auth/token/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource when I consume it on the front end?
You need to call app.UseCors() before app.UseAuthentication() because your code at the moment is trying to authenticate before the CORS policy is being applied.
Your Configure method should look like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Moved this line
app.UseCors("EnableCORS");
app.UseAuthentication();
//app.UseHttpsRedirection();
app.UseMvc();
}
See the documentation on middleware order and recommended order for common services

ASP.NET Core - can't get simple bearer token auth working

I am building an API with ASP.NET Core 2, and I am trying to get a simple auth example that uses a Bearer token to work.
First, here is my Startup code...
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "mydomain.com",
ValidAudience = "mydomain.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("THESECRETKEY THESECRETKEY THESECRETKEY THESECRETKEY"))
};
});
// goes last
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
app.UseStatusCodePages();
// goes last
app.UseMvc();
}
}
Then I have an Auth controller, that returns the token...
[Route("api/[controller]")]
public class AuthController : Controller
{
[AllowAnonymous]
[HttpPost("RequestToken")]
public IActionResult RequestToken([FromBody] TokenRequest request)
{
if (request.Username == "theuser" && request.Password == "thepassword")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("THESECRETKEY THESECRETKEY THESECRETKEY THESECRETKEY"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "mydomain.com",
audience: "mydomain.com",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
return BadRequest("Could not verify username and password");
}
}
public class TokenRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
So in Postman you can see I get a token back...
And then I try GET from a Values controller...
[Route("api/[controller]")]
[Authorize]
public class ValuesController : Controller
{
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
}
If I add the [Anonymous] attribute, it works fine. However, when it requires authorization, I get a 401...
You haven't referenced the Authentication middleware in your Startup.cs
You can reference it by adding app.UseAuthentication(); preferably just before the app.UseMvc();
Here's how your Startup.cs's Configure method should look like:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
app.UseStatusCodePages();
app.UseAuthentication();
app.UseMvc();
}
You can read more into middleware here and more into authorization with ASP.NET Core here.
You should also look here for everything else about ASP.NET Core