Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用从Login_View.cshtml检索的数据进行令牌身份验证_C#_Asp.net Mvc_Authentication_Asp.net Web Api_Token - Fatal编程技术网

C# 如何使用从Login_View.cshtml检索的数据进行令牌身份验证

C# 如何使用从Login_View.cshtml检索的数据进行令牌身份验证,c#,asp.net-mvc,authentication,asp.net-web-api,token,C#,Asp.net Mvc,Authentication,Asp.net Web Api,Token,我目前正在使用ASP.NET MVC 5 WebAPI 2作为我的最终项目,因此我创建了我的Login_View.cshtml,然后遵循一些关于令牌身份验证的教程,但他们只使用POSTMAN手动键入用户名和密码来测试访问权限,而我需要在此视图中键入用户名和密码。 以下是我的登录\u View.cs代码: <html> <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/boot

我目前正在使用ASP.NET MVC 5 WebAPI 2作为我的最终项目,因此我创建了我的Login_View.cshtml,然后遵循一些关于令牌身份验证的教程,但他们只使用POSTMAN手动键入用户名和密码来测试访问权限,而我需要在此视图中键入用户名和密码。

以下是我的登录\u View.cs代码:

<html>
<head>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
<img src="~/fonts/linee.png"  />
    <div class="wrapper fadeInDown">
        <div id="formContent">
            <form method="post" asp-controller="HomeController" action="/Home/ControlLogin">
                <input type="text" id="login" class="fadeIn second" name="user" placeholder="Nom d'utilisateur" required/>
                <input type="password" id="password" class="fadeIn third" name="pass" placeholder="Mot de passe" required/>
                <input type="submit" class="fadeIn fourth" value="S'identifier" />
            </form>

            <!-- Remind Passowrd -->
            <div id="formFooter">
                <a class="underlineHover" href="#">Forgot Password?</a>
            </div>
        </div>
    </div>
 <img src="~/fonts/line2.png" />
</body>
</html>
这是MyAuthProvider.cs代码:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new MyAuthProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}
public class MyAuthProvider : OAuthAuthorizationServerProvider
    {

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            string connetionString = null;

            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            try
             {
             con.Open();
             SqlCommand cmd = new SqlCommand("select * from Users where email=@email and password=@pwd", con);
             cmd.Parameters.AddWithValue("@email", context.UserName);
             cmd.Parameters.AddWithValue("@pwd", context.Password);

             SqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
                {
                    string role = reader["role"].ToString();
                    string name = reader["fullname"].ToString();

                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    identity.AddClaim(new Claim(ClaimTypes.Name, name));
                    context.Validated(identity);
                }
                else
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    context.Rejected();
                }
            }
            catch (Exception ex)
            {
                context.SetError("connexion Problems", ex.Message.ToString());
            }
        }
    }

}
当我在POSTMAN上测试时,此代码非常有效,但我想使用此登录视图中键入的电子邮件和密码,在您的表单中使用令牌身份验证使用:

        @using(Html.BeginForm("ActionName", "Controller", FormMethod.Post, new { id = "id" }))
        {
            @Html.TextBoxFor(m => m.login, new { @class = "form-control" })
            @Html.PasswordFor(m => m.password, new { @class = "fadeIn third" })
            <input type = "submit" class="fadeIn fourth" value="S'identifier" />
        }
@使用(Html.BeginForm(“ActionName”、“Controller”、FormMethod.Post、new{id=“id”}))
{
@TextBoxFor(m=>m.login,新的{@class=“form control”})
@Html.PasswordFor(m=>m.password,新的{@class=“fadeIn third”})
}

然后,您可以从模型中获取控制器操作中的名称和密码,以创建身份验证令牌

经过几天的尝试和使用代码,我终于找到了一个解决方案,我实际上使用了我在这里找到的代码

我将其修改为与视图一起使用,以下是控制器中的代码:

public ActionResult ControLogin(string user, string pass)
        {
            var t = JsonConvert.DeserializeObject<Token>("");

            if (user == "" || pass == "")
            {
                MessageBox.Show("FAILED", "failed");
                return RedirectToAction("Login");

            }
            else
            {

                var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ),
                        new KeyValuePair<string, string>( "username", user),
                        new KeyValuePair<string, string> ( "Password", pass )
                    };
                var content = new FormUrlEncodedContent(pairs);

                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                using (var client = new HttpClient())
                {
                    var response = client.PostAsync("https://localhost:44396/" + "Token", content).Result;
                    String token = response.Content.ReadAsStringAsync().Result;

                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        t = JsonConvert.DeserializeObject<Token>(token);

                        client.DefaultRequestHeaders.Clear();
                        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
                    }

                }
                if (t.access_token == null)
                {
                    MessageBox.Show("User Not Found", "ERROR");
                    return RedirectToAction("Login");

                }
                else
                {
                    return RedirectToAction("Homeadmin");
                }
            }
        }
public-ActionResult-ControLogin(字符串用户,字符串传递)
{
var t=JsonConvert.DeserializeObject(“”);
如果(用户==“”| |通过==“”)
{
MessageBox.Show(“失败”、“失败”);
返回重定向操作(“登录”);
}
其他的
{
var pairs=新列表
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,用户),
新的KeyValuePair(“密码”,通过)
};
var内容=新FormUrlEncodedContent(成对);
ServicePointManager.ServerCertificateValidationCallback+=(发件人、证书、链、sslPolicyErrors)=>true;
使用(var client=new HttpClient())
{
var response=client.PostAsync(“https://localhost:44396/“+”标记“,内容)。结果;
字符串标记=response.Content.ReadAsStringAsync().Result;
如果(!string.IsNullOrWhiteSpace(标记))
{
t=JsonConvert.DeserializeObject(令牌);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add(“授权”、“承载人”+t.access\u令牌);
}
}
if(t.access_token==null)
{
MessageBox.Show(“未找到用户”,“错误”);
返回重定向操作(“登录”);
}
其他的
{
返回重定向到操作(“Homeadmin”);
}
}
}

我希望这将帮助其他人(^ ^)

我已经在控制器中获得用户名和密码,但我的问题是我不知道如何将它们传递给MyAuthProvider.cs类中使用的上下文