使用以下登录方法和" Startup.cs",具有[Authorize(Roles =" Administrator")]属性的控制器工作正常但需要经过身份验证的用户和不关心他们的角色回归"状态代码:401 Unauthorized"。
登录方式:
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。
答案 0 :(得分:0)
LogIn方法稍有改动,问题就解决了。
{{1}}
检查注释部分以了解更改。