I am working with Web API and ASP.NET MVC.
I'm passing a wrong username and password in the address bar then also give the success message that is the issue
This record is not available in my table:
I am creating 2 projects one for Web API framework scaffolding and second is a normal empty ASP.NET MVC project.
Normal empty ASP.NET MVC project (not using Entity Framework)
globalvariable.cs:
namespace Mvc
{
public static class globalvariable
{
public static HttpClient webapiclient = new HttpClient();
static globalvariable()
{
webapiclient.BaseAddress = new Uri("https://localhost:0000/api/");
webapiclient.DefaultRequestHeaders.Clear();
webapiclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
}
empsController.cs:
namespace Mvc.Controllers
{
public class empsController : Controller
{
public JsonResult Index()
{
IEnumerable<mvcempmodel> empList;
HttpResponseMessage response = globalvariable.webapiclient.GetAsync("emps").Result;
empList = response.Content.ReadAsAsync<IEnumerable<mvcempmodel>>().Result;
//return View(empList);
return Json(empList, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult Login(string username, string password)
{
if (username == "" || username == null)
{
var data = new
{
message = "Enter Username ",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else if (password == "" || password == null)
{
var data = new
{
message = "Enter Password",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
var userdata = "select * from emp where username='" + username + "'and password='" + password + "'".First();
if (userdata != null)
{
var data = new
{
message = "Success",
data = new { username }
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
var data = new
{
message = "Username and Password incorrect ",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
}
}
}
}
Web API project (using Entity Framework)
empsController.cs:
namespace WebApi.Controllers
{
public class empsController : ApiController
{
private empdbEntities db = new empdbEntities();
// GET: api/emps
public IQueryable<emp> Getemps()
{
return db.emps;
}
// GET: api/emps/5
[ResponseType(typeof(emp))]
public IHttpActionResult Getemp(int id)
{
emp emp = db.emps.Find(id);
if (emp == null)
{
return NotFound();
}
return Ok(emp);
}
}
}
What I want to If user enter true credential then give the success message and when the user enter false credential then give the username and password incorrect message
Here I think my query is wrong
var userdata = "select * from emp where username='" + username + "'and password='" + password + "'".First();
Please help
You can check this to url (as you mentioned you are a beginner and wanted to know how to query a database)
In asp.net, You can query a database using
Entity framework (the second link shows how to query local db using Entity framework)
Dapper (micro orm, fast)
ADO.net (old school style and required to write a lot of boiler plate code)
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string
To query Sql server database at remote or local server, just change the connection string.
Related
I have a project that contains 2 applications that are structured like this:
App
AppAPI
AppAPI references App and calls AuthenticateUser within the ApiAccountController class from App.
AppAPI
public class TokenController : ApiController
{
// This is naive endpoint for demo, it should use Basic authentication to provide token or POST request
// GET api/token/
public string Get(string username, string password)
{
if (CheckUser(username, password))
{
return JwtManager.GenerateToken(username);
}
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
private bool CheckUser(string username, string password)
{
ApiAccountController accountController = new ApiAccountController();
return accountController.AuthenticateUser(username,password);
}
}
App
ApplicationDbContext dbContext = new ApplicationDbContext();
Logger log = LogManager.GetCurrentClassLogger();
PasswordHasher passwordHasher = new PasswordHasher();
// GET: Account
public bool AuthenticateUser(String username, String password)
{
try
{
var user = dbContext.Users.FirstOrDefault(u => u.UserName == username);
//var user = dbContext.Users.Count(u => u.UserName == username);
if (user == null)
{
log.Error(username + " not found");
return false;
}
else
{
var result = passwordHasher.VerifyHashedPassword(user.PasswordHash, password);
if (result == PasswordVerificationResult.Success)
{
return true;
}
else
{
log.Error("Invalid password for user: " + username);
return false;
}
}
//return false;
}
catch (Exception e)
{
log.Error(e, "Exception found for user: " + username);
return false;
}
}
The expected behaviour is for me to use Postman to connect to AppApi like this
http://localhost:9000/api/token?username=user#one.com&password=P#ssw0rd
and for it to authenticate this user.
However, for some reason this has been failing by returning null even though there is already a user that has been created.
I need to create a authentication for my MVC Application and WebAPI.
I have the user credential details & role information in a separate table in database. Can anyone suggest which model i can use to achieve this.
Thanks
Which Web Api are you using if it is 2 than try below code, and let me know if i could help you more, because i had same scenario like you have
you have to create a custom authorization filter and call it above ActionMethod,
Create a different class in your project and change build mode in Compile
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public static bool VaidateUserRoleWise(string username, string password, int RoleId)
{
//DO DATABASE CONNECTION DO QUERY HERE
if (Username == username && Password == password)
{
return true;
}
else
{
return false;
}
}
public override void OnAuthorization(QuizzrApi.Controllers.QuizzrController.InputParamAdminLogin LoginDetails)
{
System.Web.Http.Controllers.HttpActionContext actionContext = null;
if (LoginDetails == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
//Bellow is the static method called above will return true or false if user matches
if (!VaidateUserRoleWise(LoginDetails.UserName, LoginDetails.Password, 1))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
base.OnAuthorization(actionContext);
}
}
In controller :
[Route("AuthorizeSystemAdmin")]
[HttpPost]
[BasicAuthentication]
public HttpResponseMessage Login([FromBody] InputParamAdminLogin AdminLoginInput)
{
//do your logic here
}
I have an Index controller that gets user data and saves it to a model in my application. This happens during the "CustomAuth" call below.
[CustomAuth(group = "Role-View")]
public class IndexController : Controller
{
public ActionResult Index()
{
try
{
//call to progService
return View();
}
catch (Exception e)
{
Error.Log(e, log.LogGuid, this.User.Identity.Name);
return View();
}
}
}
Here is the code I am using to assign things to my model.
public void CheckForUser(string username, string firstName, string lastName, string emailAddress, string phoneNumber)
{
var userDataModel = new UserDataModel();
userDataModel.username = username;
userDataModel.firstName = firstName;
userDataModel.lastName = lastName;
userDataModel.emailAddress = emailAddress;
userDataModel.phoneNumber = phoneNumber;
var userexists = db.PARTies.Any(x => x.ABBR_NM == username);
if (userexists)
{
var updateUser = db.PARTies.SingleOrDefault(x => x.ABBR_NM == username);
//Get and assign the partId to the model.
userDataModel.partyId = updateUser.PARTY_ID;
//Update any fields that are relevant.
updateUser.FIRST_NM = userDataModel.firstName;
updateUser.LAST_NM = userDataModel.lastName;
updateUser.ABBR_NM = userDataModel.username;
updateUser.FULL_NM = (userDataModel.firstName + " " + userDataModel.lastName);
//Save the updated Data to the database.
db.SaveChanges();
My issue is that once this is complete, I can't seem to access the user data again. I would like to call my database and use the userDataModel.partyId from the model like so. (In a service in my Business Layer.)
public List<WizardProgModel> FetchTable()
{
return db.WIZARD_PRGRSS.Where(x => x.PARTY_ID == userDataModel.partyId);
}
I am probably missing something dumb here but shouldn't I be able to reference anything I assign in my model while the application is running? Everything up to this point is server side so the View shouldn't come into play at this point.
Thank you.
You don't need to declare the model to save it as a new db entity just use the parameters from you method directly and once in your service simply go fetch the entity back from the db. and if you need it as a model in the service fetch it like so:
var userModel = db.PARTies.FirstOrDefault(x => x.ABBR_NM == username).Select(e => new = UserDataModel {
username = username,
firstName = firstName,
lastName = lastName,
emailAddress = emailAddress,
phoneNumber = phoneNumber
});
Make your read method accept the Party Id as a parameter, For how you will get it to the service I can't tell you because I simply don't have the scope of your application/solution.
public List<WizardProgModel> FetchTable(int partyId)
{
return db.WIZARD_PRGRSS.Where(x => x.PARTY_ID == partyId);
}
I'm creating methods in my web api to be able to remove users, but the same method that I'm using for my other controller is working? I'm reciving a 405 - method not allowed.
PostController (working):
public IHttpActionResult DeletePost(int id)
{
Post post = controller.Post(id);
if (post == null)
{
return NotFound();
}
controller.DeletePost(id);
return Ok(post);
}
UserController (not working):
public IHttpActionResult DeleteUser(string username)
{
User user = controller.User(username);
if (user == null)
{
return NotFound();
}
controller.DeleteUser(username);
return Ok(user);
}
This is the DAL for the Delete method of the UserController:
public void DeleteUser(string username)
{
SqlConnection con = new SqlConnection("Server=localhost;Database=X;User Id=X;Password=X;");
string sql = "DELETE FROM [User] WHERE Username=#Username";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
}
NOTE: The query works directly in SQL Management Studio
Edit for angular part (note: they are in the same controller and template):
$scope.delete = function (id) {
Post.delete({ id: id }, function () {
$scope.getPosts();
}
);
};
$scope.deleteUser = function (id) {
User.delete({ id: id }, function () {
console.log("delete button triggered");
$scope.getUsers();
}
);
};
I'm creating one asp.net mvc 4.0 application. in which I want to use default asp.net form authentication.
I've created all required tables in ms sql for storing roles and username password.
help me earliest possible. I'm stuck at this point.
if you are using asp.net mvc 4.0 form authentication with required tables in mssql server.
you can create new user as follows.
[AllowAnonymous]
public JsonResult RegisterUser()
{
String Uid = Request.QueryString["id"];
String Pass = Request.QueryString["pass"];
String username = Uid;
String password = Pass;
try
{
//Session["username"] = username;
Membership.CreateUser(Uid, Pass);
return Json("success", JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json("falied", JsonRequestBehavior.AllowGet);
}
}
and you can validate the user in the same as follows.
[AllowAnonymous]
public JsonResult ValidateUser()
{
String Uid = Request.QueryString["id"];
String Pass = Request.QueryString["pass"];
String username = Uid;
String password = Pass;
if (Membership.ValidateUser(username, password))
{
//Session["username"] = username;
FormsAuthentication.RedirectFromLoginPage(username, true);
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("falied", JsonRequestBehavior.AllowGet);
}
}
Hope this will help you.