Reputation: 3
I have been trying to implement basic authentication into my Razor 3.0 web app.
I have a user being signed in via SignInAsync(), however when trying to redirect to a page that requires Authorization, the page does not load. Instead the Login page reloads, with the URL being updated with a "?ReturnUrl=%Page%Path" appended.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin");
options.Conventions.AllowAnonymousToPage("/Login");
options.Conventions.AddPageRoute("/Login", "");
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
Here I am setting the Admin folder to require authorization, and allowing anonymous users to access the login page.
Login.cshtml.cs
[BindProperty]
public UserModel UserLogin { get; set; }
public async Task<IActionResult> OnPost()
{
try
{
if (ModelState.IsValid)
{
var loginInfo = apiConnector.Get();
if (loginInfo)
{
await this.SignInUser(UserLogin.Username, false);
return this.RedirectToPage("/Admin/FormOverview");
}
}
}
catch(Exception e)
{
Console.Write(e);
}
return this.Page();
}
private async Task SignInUser(string username, bool isPersistant)
{
try
{
var claims = new List<Claim>() {
new Claim(ClaimTypes.Name, username)
};
var claimIdentities = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimPrincipal = new ClaimsPrincipal(claimIdentities);
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimPrincipal, authProperties);
}
Here I've set up a dummy API which always returns true, with the user having a Claim created them and signing them in.
I am new to Razor so I may be approaching this incorrectly, any help appreciated, thanks.
Upvotes: 0
Views: 932
Reputation: 471
Order matters
app.UseAuthentication();
app.UseAuthorization();
Upvotes: 1