[英]Authorize attribute does not work
I have downloaded the Microsoft.AspNet.Identity.Samples Pre found at: https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples 我已经下载了Microsoft.AspNet.Identity.Samples Pre, 网址为: https : //www.nuget.org/packages/Microsoft.AspNet.Identity.Samples
Also, I have also adapted a sample from GitHub. 另外,我还改编了一个来自GitHub的示例。
In both cases whenever I try to access the "RolesAdmin" ie ~/rolesadmin/ page, it kicks me back to the login page. 在这两种情况下,每当我尝试访问“ RolesAdmin”即〜/ rolesadmin /页面时,都将我带回到登录页面。
I have confirmed the user is logged in and belongs to the Admin role, so why does the Authorize attribute not permit my entry into the roleadmin page? 我已经确认用户已登录并属于Admin角色,那么为什么Authorize属性不允许我进入roleadmin页面?
namespace IdentitySample.Controllers
{
[Authorize(Roles = "Admin")]
public class RolesAdminController : Controller
...
Here's my code for confirming (ViewBag.IsLoggedIn and ViewBag.IsAdmin both come back as true once logged in: 这是我用于确认的代码(一旦登录,ViewBag.IsLoggedIn和ViewBag.IsAdmin都将返回true:
if (User.Identity.IsAuthenticated)
{
MyDbContext context = new MyDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var appUser = UserManager.FindByName("Admin");
var userIsInRole = UserManager.IsInRole(appUser.Id, "Admin");
ViewBag.IsLoggedIn = true;
ViewBag.IsAdmin = userIsInRole;
}
else
{
ViewBag.IsLoggedIn = false;
ViewBag.IsAdmin = false;
}
If there is a good sample code for ASP.NET Identity 2.1.0 out there - please let me know. 如果那里有ASP.NET Identity 2.1.0的良好示例代码-请让我知道。
Why can I not access this controller? 为什么我不能访问该控制器?
I have looked at this page: MVC 5 Asp.Net Identity Authorize Attribute error 我查看了此页面: MVC 5 Asp.Net身份授权属性错误
And this page: ASP.NET Identity - Confusion about [Authorize] And RoleManager 本页: ASP.NET身份-关于[授权]和RoleManager的混淆
And this page: Custom Forms Authentication + MVC3 + AuthorizeAttribute 本页: 自定义表单身份验证+ MVC3 + AuthorizeAttribute
None of it seems to help. 似乎没有帮助。
Notes: I am using VS2012 with the latest tools update, SQL Server 2012 express. 注意:我正在将VS2012与最新的工具更新(SQL Server 2012 Express)一起使用。 Also, in one of the code samples you will see I have created a user called Admin and role called Admin - I just copied the code I have to admit.
另外,在其中一个代码示例中,您将看到我创建了一个名为Admin的用户和一个名为Admin的角色-我只是复制了我必须承认的代码。
Relevant bit of web.config seems to make no difference: web.config的相关位似乎没有什么区别:
<membership>
<providers>
<clear />
</providers>
</membership>
<roleManager enabled="true">
<providers>
<clear />
</providers>
</roleManager>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="RoleManager" />
</modules>
</system.webServer>
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute()); // Added this in a vein attempt
}
}
Start-up class 入门班
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Login code on AccountController: AccountController上的登录代码:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
SignInAsync code: 登录异步代码:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
// Add more custom claims here if you want. Eg HomeTown can be a claim for the User
//var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
//identity.AddClaim(homeclaim);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
I would expect the Microsoft sample to work out of the box which is what I find most baffling... 我希望Microsoft示例可以立即使用,这是我最困惑的地方。
Answer: 回答:
1) Use https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples -Pre 1)使用https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples -Pre
Don't register in your website and then expect to gain access to your controller protected by Authorize attribute with Roles set to Admin. 不要在您的网站上注册,然后希望获得对您的控制器的访问,该控制器受Roleize设置为Admin的Authorize属性保护。 Your new user will not be assigned to the Admin role.
您的新用户将不会被分配为管理员角色。 Use the default login: admin@example.com with password Admin@123456
使用默认登录名:admin@example.com,密码为Admin @ 123456
2) I found this github sample ( https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample ) linked from the asp.net website to be quite either broken (because it did not build without manually adding the word "class" to a class inheritance) or simply out of date. 2)我发现从asp.net网站链接的这个github示例( https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample )相当不完整(因为如果没有手动添加“类”继承到类继承)或完全过时。
3) Be wary of web.config and sub-web.config configuration when copying from the sample. 3)从示例复制时,请警惕web.config和sub-web.config配置。
4) You may wish not to integrate some of my code above as it is not in the sample (the one that works). 4)您可能不希望在上面集成我的某些代码,因为它不在示例中(有效的代码)。
Now I may continue, unhindered to build my sensor arduino yun based signalr logging, reporting and visualisation website for my home/brewing/gardening projects. 现在,我可以不受阻碍地继续为我的家庭/饲养/园艺项目构建基于arduino yun传感器的信号记录,报告和可视化网站。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.