ASP.NET身份集成项目时,与无身份验证创建 [英] ASP.NET Identity Integration when project is created with no authentication

查看:313
本文介绍了ASP.NET身份集成项目时,与无身份验证创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有身份的问题,我不是很熟悉。不久前,我开始,最初并不意味着必须连接到它的任何身份验证的新项​​目。然而,随着项目的成长,我们发现,我们应该实现它。由于最初没有设立这样,我创建了一个表格进行登录。

I have an issue with Identity and I am not very familiar with it. Not too long ago I started a new project that was originally not meant to have any authentication attached to it. However, as the project grew we found that we should implement it. Since it wasn't originally set up that way I created a form for a login.

我找到了这个问题的答案,并实现了它:

I found the answer to this question and implemented it:

<一个href=\"http://stackoverflow.com/questions/31584506/how-to-implement-custom-authentication-in-asp-net-mvc-5\">How在ASP.NET中实现MVC 5 自定义验证

但它不工作,我不知道为什么。

However it is not working and I do not know why.

下面是我的code:

没什么,看看这里只是一个简单的形式。

Nothing much to see here it's just a plain form.

@{
    ViewBag.Title = "Login";
}

<div class="container">

<h2>Login</h2>

<br />

@using (Html.BeginForm("Login", "Main"))
{
    <div class="row">
        <div class="form-group col-xs-6">
            @Html.Label("Username", htmlAttributes: new { @class = "control-label col-sm-3" })
            <div class="col-sm-8">
                @Html.TextBox("username", null, new { @class = "form-control" })
                @*Html.ValidationMessageFor(model => model.EnrollmentOption, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group col-xs-6">
        </div>

    </div>

    <div class="row">
        <div class="form-group col-xs-6">
            @Html.Label("Password", htmlAttributes: new { @class = "control-label col-sm-3" })
            <div class="col-sm-8">
                @Html.Password("password", null, new { @class = "form-control" })
                @*Html.ValidationMessageFor(model => model.EffectiveDate, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group col-xs-6">
        </div>

    </div>

    <div class="row">
        <div class="form-group">
            <div class="col-md-offset-6 col-sm-5">
                <input type="submit" id="login" value="Sign in" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

它实现的操作是这样的,这个重要得多:

The action implemented for it is this one, this matters much more:

    [HttpPost]
    public ActionResult Login(string username, string password)
    {
        if (isLoginValid(username, password))
        {
            var ident = new ClaimsIdentity(
              new[] { 
          // adding following 2 claim just for supporting default antiforgery provider
          new Claim(ClaimTypes.NameIdentifier, username),
          new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

          new Claim(ClaimTypes.Name,username),

          // No roles needed for now...
              },
              DefaultAuthenticationTypes.ApplicationCookie);

            HttpContext.GetOwinContext().Authentication.SignIn(
               new AuthenticationProperties { IsPersistent = false }, ident);
            return RedirectToAction("QuoteSearch"); // auth succeed 
        }
        else
        { 
            // invalid username or password
            ModelState.AddModelError("", "Invalid username or password");
            return View();
        }
    }

和还有的isLoginValid功能(现在它被设置为使用硬codeD登录)

And there's the isLoginValid function (For now it's set to use a hardcoded login)

    [NonAction]
    private bool isLoginValid(string user, string password)
    {
        return (user.ToLower() == "someUser" && password.ToLower() == "myPassword");
    }

我不很懂索赔或身份如何工作的下面。我也确保虽然将所有必要的参考。当使用我的行动的授权属性在登录后重定向我从IIS中未经授权的请求。是不是有什么毛病我code?

I do not know very much of claims or how Identity works underneath. I did make sure of adding all the necessary references though. When using the authorize attribute on my actions after the login redirects I get an unauthorized request from IIS. Is there something wrong with my code?

我应该怎么更改或修正,以便能够使用Identity的授权部分?

What should I change or fix to be able to use the Authorization part of Identity?

谢谢,

推荐答案

一些故障排除和感谢guysherman的评论后,我能找到解决方案。既然我已经创建的解决方案,在考虑任何身份验证我删除了,包括我的App_Start文件夹引用和必要OWIN配置code的。

After some troubleshooting and thanks to guysherman's comment I was able to find the solution. Since I had created the solution with no authentication in mind I removed the includes of references and necessary OWIN configuration code in my App_Start folder.

正因为如此,没有什么身份的定义,并从授权部分没有发生,尽管事实是登录工作完全。通过创建一个新的项目并添加所需的所有code要配置身份,我是能够使用授权属性正确。不用任何问题。

Because of this, nothing in Identity was defined and nothing from the authorization part occurred despite the fact that the login was working perfectly. By creating a new project and adding all the needed code to configure Identity, I was able to use the Authorize attribute properly. without any problems whatsoever.

(这个答案适用于ASP.NET 4.6,我想这是ASP.NET核心不同的处理)

(This answer applies for ASP.NET 4.6, I suppose this is handled differently for ASP.NET Core)

更新:

要做出这样的回答更好,我想我应该阐述更进我做了什么,使其工作。

To make this answer better I thought I should elaborate more into what I did to make it work.

在创建带有标识的新项目,你会看到有,如果你选择不添加它未创建多个文件,你需要这些,他们大多都存储在App_Start。

When creating a new project with identity you will see that there are several files that aren't created if you choose to not add it, you will need those, most of them are stored in App_Start.

App_Start一个正常的ASP.NET项目

我抄我没有足够的文件,改变了命名空间,以配合我的实际项目。一旦这样做,它变得清楚它的NuGet包我失踪了,所以我说还没有加我的人。

I copied the files I did not have and changed the namespaces to match my actual project. Once doing that it was made apparent which nuget packages I was missing, so I added the ones I hadn't yet added.

Startup.Auth.cs将有一个关键的功能定义身份工作:

Startup.Auth.cs will have the definition for a key function for identity to work:

ConfigureAuth

ConfigureAuth

该功能必须在启动类调用。在配置方法

This function must be called in the startup class. in the configuration method.

在这里输入的形象描述

在这里输入的形象描述

最后,一切工作,还必须包括在模型文件夹内正常创建的文件IdentityModel.cs。就我而言,我把所有的模型在不同的项目,所以我把班上有,并添加上IdentityConfig.cs引用,这样的类将认识到IdentityModel存在。

Finally, for everything to work, you must also include the file IdentityModel.cs that is created normally inside the Models folder. In my case, I placed all models in a different project, so I placed the class there and added references on IdentityConfig.cs so that the class would recognize that the IdentityModel exists.

在这里输入的形象描述

和仅此而已。在我来说,我有很多的身份与尝试连接到数据库去寻找用户的问题,因为身份没有配置数据库,我的应用程序崩溃开始,由于未能DB连接。删除第三图像在标有红色的线条使得它为我工作。我不想身份的数据库连接,因为我有我自己的用户操作,这可能不是别人的情况。

And that was all. In my case I had a lot of problems with identity trying to connect to the db to look for users, since Identity didn't have a database configured, my app started crashing due to failed db connections. Removing the lines marked with red in the third image made it work for me. I did not want identity's db connection since I have my own user handling, this might not be someone else's case.

这篇关于ASP.NET身份集成项目时,与无身份验证创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆