Reset Password in ASP.NET MVC - asp.net

I am implementing my own reset password in ASP.NET. In reset password, first I create a random string and mail it to user email.For the link in email like http://xyz.com/account/forgot?random=xxxx&userid=xx.I created a httpget type action forgot which show return a view with input tags for passwords if randomid and userid are validated.
But in httppost type of forgot, I have confusion about the parameters.
I have forgotModel having 2 properties password and confirmpassword.If I just pass forgotmodel to httppost action, then I cannot query user from database.I think I should pass randomId as parameter.But, I am getting how to grab randomID from url of httpget action (If I do so, is it safe?)?
Please guide me, I got stuck..
Thanks in advance

Are you using like Html.BeginForm("action","controller"), If so then you will loose querystring parameters. Since HttpGet and HttpPost methods of ForGotPassword(..) have same action name, You can just use Html.BeginForm().
So, the form will post data to the page url and you will get querystring along with it.
in your http post method you can define like,
[HttpPost]
public ActionResult ForGot(ForgotModel model, string random,strung userid)
{
:
:
}
If you do not want to follow the above approach, then in httpget method write to ViewBag/ViewData and put them as hidden field in view. Then you can receive them as input to Method.
[HttpGet]
public ActionResult ForGot(string random,strung userid)
{
ViewBag.Random =random;
Viewbag.Userid =userid;
:
:
}
[HttpPost]
public ActionResult ForGot(ForgotModel model, string random,strung userid)
{
:
:
}
and , in view
#Html.BeginForm("ForGot","Account"){
:
#Html.Hidden(ViewBag.Random)
#Html.Hidden(ViewBag.Userid)
:
}

Related

ASP.NET Core 3.1: POST-REDIRECT-GET: Passing parameters

I'm trying to implement POST-REDIRECT-GET technique where I post a JSON string to my razor OnPost method. This in turn redirects to OnGet method that takes in that string parameter. How do I hide this input parameter string to my OnGet method?
Edit: I tried using ViewData but the value is always null in my OnGet method even though I set it before redirect.
public async Task<IActionResult> OnPostData(string input_JSON)
{
TempData["InputJSON"] = input_JSON;
return RedirectToPage("GetData");
}
public async Task<IActionResult> OnGetGetData()
{
string tempData = TempData["InputJSON"] as string;
//do somethig with string;
}
I do form post in my javascript and when the new window opens, I see the input_string in my URL. How do I pass parameters between methods?
https://learn.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.2#tempdata-provider-and-session-state-cookies-arent-essential
According to Microsoft, TempData provider and session state cookies aren't essential. I had to make it essential in my Startup.cs file's ConfigureServices:
services.Configure<CookieTempDataProviderOptions>(options => {
options.Cookie.IsEssential = true;
});

Send object as parameter in client.PutAsync

I am facing a problem in using PutAsync. PutAsync update an object. Below is my code. (Mongodb database)
Controller Code:
stringData = JsonConvert.SerializeObject(businessUnit); //businessUnit is updated object
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
response = client.PutAsync(baseAddress + "/api/BusinessUnit/" + businessUnit.Id, contentData).Result;
API Controller Code :
[HttpPut("{id}")]
public async Task<string> Put(string id, BusinessUnit businessUnit)
{
if (string.IsNullOrEmpty(id)) return "Invalid id !!!";
return await _businessUnitRepository.Update(id, businessUnit);
}
Given code works good but my problem is in API controller businessUnit parameter's all fields become null instead of id.
My Confusion is, if businessUnit parameter's all fields are null then why its primary key "id" is not null ??
I want to get all fields as parameter in businessUnit object from controller to api controller. How can I do it?
Thanks in advance.
Add the [FromBody] attribute to the 'businessUnit' parameter:
public async Task<string> Put(string id, [FromBody] BusinessUnit businessUnit)
This is called an Model Binding and allows to map data from HTTP requests to action method parameters:
[FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected based on content type of the request.

ASP.NET MVC 5 Attribute Routing: Url.Action returns null

I am experiencing an issue with a refactoring of our payment processing action method (called by our 3rd-party online payment provider). We have a product controller with the [Authorize] and [RoutePrefix("products")] attributes at the class level, and action methods including the following:
Product(string contractNumber) with routing attribute [Route("{productCode}")]
MakePayment(string productCode, PaymentAmountType? amountSelection, decimal? amountValue) with routing attribute [Route("{productCode}")] and [HttpPost] attribute
ProcessPayment(string productCode, string result) with routing attribute [Route("{productCode}")]
Because our payment gateway needs to be able to call our ProcessPayment action before the visitor is redirected to that same URL, we've had to refactor that to a separate controller without the [Authorize] attribute. (We already have mechanisms to prevent double-crediting a payment.)
Before this refactoring, the MakePayment action method correctly formulated the correct return URL in the following call to Url.Action():
var rawCallbackUrl = Url.Action("ProcessPayment", new { productCode = productCode });
The ProcessPayment action method has now been moved out of the product controller and into a new controller, ExternalCallbackController, which has no attributes (let alone [Authorize]), in order to avoid having an HTTP 401 response returned to the payment provider.
The route attribute on ProcessPayment is now [Route("order-processing/{productCode}/process-payment")] to avoid clashing with the RoutePrefix on the product controller. All references to this updated action method are updated to specify the ExternalCallbackController.
Manually browsing to the URL causes the breakpoint set inside ProcessPayment to be hit, so the route apparently works successfully.
The problem is that in MakePayment, the following call returns null:
var rawCallbackUrl = Url.Action("ProcessPayment", "ExternalCallback", new { productCode = productCode });
Given that I am specifying both the controller and action method, why is Url.Action(...) not returning the expected URL in the form order-processing/{productCode}/process-payment?
From Day 1, our RegisterRoutes() method in RouteConfig has had attribute routing properly initialised with
routes.MapMvcAttributeRoutes();
How can I get the correct URL returned from the call to Url.Action(...)?
Doh - I've figured out what went wrong. Despite the sanitising of names in the source code (which were specific to our client), it turns out that there was a mismatch in the following call:
var rawCallbackUrl = Url.Action("ProcessPayment", "ExternalCallback", new { productCode = productCode });
and the ProcessPayment() action method.
This is akin to the following (note the use of productNumber instead of productCode):
var rawCallbackUrl = Url.Action("ProcessPayment", "ExternalCallback", new { productNumber = productNumber });
trying to reference the action method:
[Route("order-processing/{productCode}/process-payment")]
public ActionResult ProcessPayment(string productCode, string result)
{
...
}
It also turns out that I can also use the same prefix "products" instead of "order-processing", as MVC creates one Route per attribute route in the routing table. Hope that helps others stuck in a similar situation.
I got this Error : Url.Action return null.
public async Task<IActionResult> ForgotPassword(ForgotPassword forgotPassword)
{
if (ModelState.IsValid)
{
// Find the user by email
var user = await userManager.FindByEmailAsync(forgotPassword.Email);
// If the user is found AND Email is confirmed
if (user != null && await userManager.IsEmailConfirmedAsync(user))
{
// Generate the reset password token
var token = await userManager.GeneratePasswordResetTokenAsync(user);
// Build the password reset link
var passwordResetLink = Url.Action("ResetPassword", "Account",
new { email = forgotPassword.Email, token }, Request.Scheme);
ViewBag.PRL = passwordResetLink;
// Send the user to Forgot Password Confirmation view
return View("ForgotPasswordConfirmation");
}
return View("ForgotPasswordConfirmation");
}
return View(forgotPassword);
}

Using FormsAuthentication on webMethod

I have a page that has a comment section. This section communicates to a WebMethod in order to insert a new comment.
[WebMethod]
public static bool insertComment(string commentString)
{
//userName validation here
string userName = (FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name);
return new CommentClass().InsertComment(commentString, userName);
}
The problem is: "An object reference is required for the non-static field".
I know I could send the information from a hidden field, or a div, however, that information field may be changed easily.
So which way could be used to know which user is posting, in server side?
thanks a lot!
Request object is an instance that lives in Page, so you need a reference to access this object in a static context. You can use HttpContext.Current.Request for accessing the Request in this context.
[WebMethod]
public static bool insertComment(string commentString)
{
//userName validation here
string userName =
(FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name);
return new CommentClass().InsertComment(commentString, userName);
}

Spring login need custom msg on screen

I want to display custom message which will be fetched from database when user try to login on login page. This message can be changed by administrator. So always need to be fetched from database.
We are using acegi spring.
Do anybody know how to do this?
Jaydeep.
set your login page to be served from a controller, then you can set a modelattribute with your custom message and show it on the login screen
e.g.
#ModelAttribute("customMessage")
public String populateCustomeMessage() {
String msg // Code to get message from db and set it into a string
return msg;
}
#RequestMapping(value = "/login.html", method = RequestMethod.GET)
public String handleRequest() {
return "login";
}
Following link somewhat discusses on the topic you need (but not fetching from database)
how to display custom error message in jsp for spring security auth exception

Resources