【发布时间】:2018-02-14 14:49:21
【问题描述】:
使用以下登录方法和“Startup.cs”,具有 [Authorize(Roles = "Administrator")] 属性的控制器工作正常,但需要经过身份验证的用户且不关心其角色的控制器返回“状态代码:401 未授权”。
登录方式:
public async void LogOn(IUser user, string domain, bool remember, TimeSpan timeout)
{
var context = AccessorsHelper.HttpContextAccessor.HttpContext;
await context.SignOutAsync(IdentityConstants.ApplicationScheme);
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.GetId().ToString())
};
claims.AddRange(user.GetRoles().Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));
await context.SignInAsync(IdentityConstants.ApplicationScheme,
new ClaimsPrincipal(new ClaimsIdentity(claims)),
new AuthenticationProperties
{
IsPersistent = remember,
ExpiresUtc = DateTimeOffset.UtcNow.Add(timeout)
});
}
Startup.cs:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.InjectOliveDependencies();
var builder = services.AddMvc(options => {
options.ModelBinderProviders.Insert(0, new Olive.Mvc.OliveBinderProvider());
//options.ModelBinderProviders.Insert(0, new TestBinderProvider());
})
.ConfigureApplicationPartManager(manager =>
{
var oldMetadataReferenceFeatureProvider = manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider);
manager.FeatureProviders.Remove(oldMetadataReferenceFeatureProvider);
manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
}); ;
//ConfigureMvc(builder);
services.Configure<RazorViewEngineOptions>(options => {
options.ViewLocationExpanders.Add(new ViewLocationExpander());
});
services.AddSingleton<IUserStore<User>, UserStore>();
services.AddSingleton<IRoleStore<string>, RoleStore>();
services.AddIdentity<User, string>();
services.AddAuthentication(IdentityConstants.ApplicationScheme);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.ConfigureOliveDependencies(env);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(routes =>
{
//routes.MapRoute(
// name: "default",
// template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
另外,我使用的是 ASP.Net Core 2.0。
【问题讨论】:
-
LogOn方法真的需要[Authorize]属性吗?它应该允许匿名访问每个尝试登录的人... -
@BalagurunathanMarimuthu 我的
LogOn方法没有[Authotize]属性。我只是提供方法,因为我认为它应该有问题。
标签: c# authentication asp.net-core authorization asp.net-core-mvc