Global authorization Config in Startup.cs Not working
Hi,
I want to configure global authorization for all actions in all my controllers (Forcing it to go through my Account Controller). I am using the below piece of code from the Step_4_Simple_Policies lab project from AuthorizationLab solution.
Startup.cs: services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); });
public class HomeController : Controller { // GET: // public IActionResult Index() { return View(); } }
I also went through the tutorial explanation (Please Refer Step 2 Authorize all Things heading) (https://github.com/blowdart/AspNetAuthorizationWorkshop )
Based on my understanding, i expect the below behavior.
Expected Behavior: After i remove Authorize tag from my Controller, adding global authorization code in startup.cs, prefixing [AllowAnonymous] tag in my account controller, all actions should go via my Login action in my Account controller for authorization
Current Behavior:
System doesn't hit Account Controller login action. This indicates global authorization configuration is not working.
Please let me know if i am missing something.
PS: I have latest RTM core libraries with VS Update 3.
Thanks, Valliappan
I can't repro this behavior.
What i tried:
- New template app using RTM bits, individual authentication.
- Replace AddMvc with:
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
When I run the app, and I see the Login page redirected to automatically.
Hi Haok,
Thanks for your quick response. I am using Windows Authentication project but only certain windows users have access to our tool (requirement). Within the project, i am using UseCookieAuthentication.
I am not able to upload my zipped sample project in this forum, so pasting contents.
AccountController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Authentication; using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApplication14.Controllers
{
[AllowAnonymous]
public class AccountController : Controller
{
public async Task
claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
var userIdentity = new ClaimsIdentity("SuperSecureLogin");
userIdentity.AddClaims(claims);
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToLocal(returnUrl);
}
public IActionResult Forbidden()
{
return View();
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
}
Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Http;
namespace WebApplication14 { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
**services.AddAuthorization(options =>
{
options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator"));
options.AddPolicy("ViewerOnly", policy => policy.RequireRole("Viewer"));
});**
**services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});**
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
**app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});**
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
HomeController.cs
public class HomeController : Controller { public IActionResult Index() { return View(); }
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
Expected Behavior: After i remove Authorize tag from my Controller, adding global authorization code in startup.cs, prefixing [AllowAnonymous] tag in my account controller, all actions should go via my Login action in my Account controller for authorization
Current Behavior:
System doesn't hit Account Controller login action. This indicates global authorization configuration is not working.
Please let me know if i am missing something.
If you are using windows auth, require authenticated user passes. so that's why its not going to the login screen.