授权属性不起作用
我想添加一个简单的登录。所以我认为最好的方法是在数据库中添加凭据,然后查询该凭据,以及您登录的用户名和密码是否匹配。这是有效的,它查询数据库,您登录并重定向到主页。然后我尝试通过该网址访问主页,发现无需登录即可访问主页。因此,我认为我应该使用
[Authorize]
家庭控制器上的属性,因为我不希望未经授权的用户访问它,因此应该将其重定向回登录页面。这是行不通的。当我在控制器上使用授权时,我在应用程序中收到错误。
Object reference not set to an instance of an object.
在 web.config 中,它看起来像这样:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="2880" /> <-- I have changed the login url to my login controller.
</authentication>
我的登录控制器是这样的。
public ActionResult Index(UserModel model) <-- I query the db in the model.
{
if (!ModelState.IsValid)
{
return View(model);
}
if(!model.IsAdmin(model.UserName, model.Password))
{
ModelState.AddModelError("username", "you are not a admin");
return View(model);
}
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
那么如何正确使用这个 Authorize 属性呢?我可以像现在这样使用它吗?我在 web.config 中遗漏了什么吗? 问候!
对此进行一些更新。由于它不起作用,我将其添加到 web.config 中:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="5">
</forms>
</authentication>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
userIsOnlineTimeWindow="2"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
以及具有硬编码凭据的membershipprovider:
public class MyMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (username.Equals("user", StringComparison.CurrentCultureIgnoreCase) && password.Equals("myPassword"))
return true;
else
return false;
}
然后我尝试使用 Authorization 属性装饰我的 HomeController,如下所示:
[Authorize()]
public class HomeController : Controller
{}
但仍然遇到相同的错误。我的意思是我可以登录,但是当我到达“主页”时,我收到与以前相同的错误。这到底是什么名字?这有什么线索吗?!
问候!
I wanted to add a simple login. So I thought the best way would be to add the credentials in a database and then query that and if the username and password mathches you get logged in. This is working, well it querys the db and you get logged in and redirected to home. Then I tried accessing home through the url and noticed that I can do that without login. So then I figured that I should use the
[Authorize]
attribute on the Home Controller as I don't want unauthorized users to access it so the should be redirected back to the login page. This does not work. when I use authorize on the controller I get a error in the application.
Object reference not set to an instance of an object.
In the web.config it looks like this:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="2880" /> <-- I have changed the login url to my login controller.
</authentication>
And my login controller like this.
public ActionResult Index(UserModel model) <-- I query the db in the model.
{
if (!ModelState.IsValid)
{
return View(model);
}
if(!model.IsAdmin(model.UserName, model.Password))
{
ModelState.AddModelError("username", "you are not a admin");
return View(model);
}
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
So how is the proper way to use this Authorize attribute? Can I even use it the way I'm using it? Am I missing something in the web.config?
Regards!
Some update to this. As it was not working I added this to the web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="5">
</forms>
</authentication>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
userIsOnlineTimeWindow="2"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
And a membershipprovider with hardcoded credentials:
public class MyMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (username.Equals("user", StringComparison.CurrentCultureIgnoreCase) && password.Equals("myPassword"))
return true;
else
return false;
}
Then I tried decorating my HomeController with the Authorization attribute like this:
[Authorize()]
public class HomeController : Controller
{}
But still getting the same error. I mean I can login but when I reach "Home" I get the same error as before. What in earths name is this?! Any clues to this?!
Regards!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是这样的:
您正在重定向到 Home 控制器的 Index 操作,该操作期望您传入某种类型的模型(不确定,因为您还没有发布 Home 控制器 Index 操作)。当您在未指定模型的情况下调用 RedirectToAction 时,当您尝试访问该模型的任何元素时,将会导致错误,因为该模型将为空。这就是为什么
当您调用具有空模型的视图时,会经常发生这种情况。您需要更改重定向以包含控制器期望的模型:
我认为您正在尝试正确使用 [Authorize]。它只需要位于您尝试锁定的控制器操作之上。
您应该发布家庭控制器的索引操作以获得有关您的问题的更具体的答案。
The problem is this:
You are redirecting to the Index action of your Home controller which expects you to pass in a model of some type(not sure because you haven't posted the Home controller Index action). When you call the RedirectToAction without the model specified, it will cause an error when you try to access any elements of that model because the model is going to be null. That is why you get the
This happens a lot when you call a view with an null model. You need to change your redirect to include the model that the controller expects:
I think you are trying to use the [Authorize] correctly. It just needs to be above the Controller Action that you are trying to lock down.
You should post the Index action of the Home controller to get some more specific answers on your problem.
您是否提供了 HomeController 的所有代码?如果是这样,您就错过了家庭控制器的索引操作。例如
,现在您正在重定向到一个不存在的操作,这将给您带来错误。
您需要通过定义 Index 操作(如我上面所做的那样)来告诉控制器在调用 Home 控制器的 Index 操作时要执行的操作。您还需要添加一个视图,告诉控制器在调用 Index 操作后要显示哪个页面。 (您的主页)
此链接有一些非常好的教程 http://www.asp.net/mvc这让我开始使用 MVC。它可能有助于进一步解释您所做的事情出了什么问题。
Did you provide all the code for your HomeController? If so you are missing the Index action of the Home controller. e.g
Right now you are redirecting to a non-existent Action which will give you an error.
You need to tell your controller what to do when the Index action of the Home controller is called by defining the Index action as I did above. You will also need to add a View that tells the controller what page to display after the Index action is called. (your home page)
This link has some really good tutorials http://www.asp.net/mvc that got me started with MVC. It may help further explain what is wrong with what you are doing.