1

I'm currently using ASP.NET MVC 5 WebAPI 2 for my final project, So i created My Login_View.cshtml and then followed some tutorials about the Token Authentification but they only use POSTMAN to test the access typing the username and password manually while i need the ones typed in this VIEW. Login_View.cshtml

Here is my Login_View.cs Code :

<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>

This is my Startup.cs code :

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);
        }
    }
}

This is MyAuthProvider.cs code :

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());
            }
        }
    }

}

This code works perfectly when i test on POSTMAN but i want to use the email and password typed in this Login_view using token authentification

Sirine
  • 11
  • 2

2 Answers2

2

In your form use:

        @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" />
        }

Then you can get the name and password in your controller action from the model to create the auth token.

dustinos3
  • 934
  • 3
  • 17
  • 27
  • I already get the username and password in the controller but my problem is i don't know how to passe them for the **context** that is used in **MyAuthProvider.cs** class – Sirine Aug 02 '19 at 16:51
0

I finally found a solution after days of trying and using code, i actually used the code i found here Answer

I modified it to use it with a View, here is the code in the controller :

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");
                }
            }
        }

I hope this will help Other people (^_^)

Sirine
  • 11
  • 2