I'm starter in .NET MVC. I want to pass a model from one controller to another controller, model contain a password. My first controller is auth method, in that I used Claims, but another controller is a vote method there I need to Post an ID, Password and Vote. Password I need in vote controller for voting confirmation in database.
My code:
My model:
public class LoginModel
{
public string IDNP { get; set; }
public string VnPassword { get; set;
}
My first controller:
public class AuthController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(LoginModel model)
{
var data = new LoginData();
data.IDNP = model.IDNP;
data.VnPassword = model.VnPassword;
var response = await session.Login(data);
if (response.Status == true)
{
var authclaims = new List<Claim>()
{
new Claim(ClaimTypes.Name, data.IDNP),
};
var authIdentity = new ClaimsIdentity(authclaims, "User Identity");
var userPrincipal = new ClaimsPrincipal(new[] {authIdentity});
HttpContext.SignInAsync(userPrincipal);
return RedirectToAction("Index", "Vote",new{pass=data.VnPassword});
}
else
{
return View();
}
}
}
My second controller:
public class VoteController : Controller
{
private IVote connection;
public VoteController()
{
var bl = new BusinessManager();
connection = bl.GetVote();
}
[Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(VoteModel vote)
{
var identity = (ClaimsIdentity)User.Identity;
var voteindex = new VoteData();
voteindex.IDNP = identity.Name;
voteindex.VnPassword = ;
voteindex.Party = vote.Party;
var response = await connection.Vote(voteindex);
if (response.Status == true)
return RedirectToAction("Index", "Home");
else
{
return RedirectToAction("Index", "Auth");
}
}
}
Actually, it's a bad idea to send Id and Password to another controller. It conflicts SRP rule.
You should have only one controller that gets and uses password.
However, if you want to use this action, you can use this
Related
I create a Name field within RoleManager and further down the class i try to call this field but it wont recognize it. it recognizes it in my view so im not sure whats happening. i had been following this tutorial https://www.youtube.com/watch?v=KGIT8P29jf4
[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
{
if (ModelState.IsValid)
{
IdentityRole identityRole = new IdentityRole
{
Name = model.RoleName
};
IdentityResult result = await roleManager.CreateAsync(identityRole);
if (result.Succeeded)
{
return RedirectToAction("ListRoles", "Administration");
}
foreach(IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
[HttpGet]
public IActionResult ListRoles()
{
var roles = roleManager.Roles;
return View(roles);
}
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var role = roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
}
var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name
};
foreach (var user in userManager.Users)
{
if (await userManager.IsInRoleAsync(user, role.Name))
{
}
}
}
The issue was that roleManager.FindByIdAsync was returning a Task. They needed to await to function call.
in asp.net core web api i have a POST method that get username and password in FormUrlEncodedContent format from client. But the "entry" parameter is null.
how can i access the username and password in Login method in web api ?
here is my code:
client:
public async Task<string> login2(string command , string username , string password)
{
string exist = string.Empty;
FormUrlEncodedContent dataForm = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("username",username),
new KeyValuePair<string, string>("password",password)
});
var resp = await http.PostAsync(command,dataForm);
exist = await resp.Content.ReadAsStringAsync();
return exist;
}
server :
public IActionResult Login([FromForm] string entry)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Console.WriteLine(entry);
return Ok(entry);
}
Create a model to hold the posted information
public class LoginModel {
public string username { get; set; }
public string password { get; set; }
}
and update the action to expect that from the from
public IActionResult Login([FromForm] LoginModel entry) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
// access the username and password
var username = entry.username;
var password = entry.password;
return Ok();
}
This is controller code for Login,
This is User Login Controller code where I authenticating user Email ID and password when user login redirected to Home Controller where I want to show user info
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin login, string ReturnUrl = ""){
string message = "";
using (LoginEntities dc = new LoginEntities()){
var v = dc.Users.Where(a => a.EmailID == login.EmailID).FirstOrDefault();
var n = dc.Users.Where(a => a.Password == login.Password).FirstOrDefault();
if (v != null || n != null ){
if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0){
int timeout = login.RememberME ? 525600 : 20;
var ticket = new FormsAuthenticationTicket(login.EmailID,login.RememberME,timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
if (Url.IsLocalUrl(ReturnUrl)){
return Redirect(ReturnUrl);
}
else{
return RedirectToAction("Index", "Home");
}
}
else{
message = "Invalid Credential Provided";
}
}
else {
message = "Invalid Credential Provided";
}
}
ViewBag.Message = message;
return View();
}
Home Controller and index action where I redirect when I login,
This is Home Controller Where I redirected After Logging successfully please some one give a code for home controller and index action where i can Get Id of user That login and and and tell me how to show that in view
public class HomeController : Controller{
LoginEntities db = new LoginEntities();
// GET: Home
[Authorize]
public ActionResult Index(){
if (Session.Contents.Count == 0){
RedirectToAction("Login", "User");
}
return View();
}
}
Updated my code below, This might or might not work coz its coded here manually not on actual VS :P
// /Controller/TestController.cs
namespace XXXX.Controllers
{
public class TestController : Controller
{
public ActionResult User()
{
String UserId = User.Identity.GetUserId().ToString();
ApplicationDbContext db = new ApplicationDbContext();
var rs = db.Users.Find(UserId);
var model = new UserViewModel
{
UserName = rs.UserName,
FirstName = rs.FirstName,
LastName = rs.LastName,
Email = rs.Email
};
db.Dispose();
return View(model);
}
}
}
// /Models/UserViewModel.cs
namespace XXXX.Models
{
public class UserViewModel
{
public string Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
// /Views/Test/User.cshtml
#model XXXX.Models.UsersCreateViewModel
<p>
#Html.Raw(Model.FirstName)
</p>
above is just a sample you can use the info further
I am working in an ASP.NET MVC 5 application. Users are able to register and login without any issues. However, when one user forgets his/her password, the forgot password process (already in place) doesn't do anything! No emails are sent to the user with a click here to reset password link.
Currently my ForgotPassword action method looks like this:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
I am guessing that is left to the developers to implement. I Googled around and found nothing that was straight forward.
What is the easiest way to allow this?
Forget password action to generate reset token:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
Reset password action to reset password based on generated token:
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
Relevent view models:
public class ResetPasswordViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public class ForgotPasswordViewModel
{
public string Email { get; set; }
}
But you need to configure Email service before sending emails.
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
return configSendGridasync(message);
}
private Task configSendGridasync(IdentityMessage message)
{
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new System.Net.Mail.MailAddress(
"you#somewhere.com", "My name");
myMessage.Subject = message.Subject;
myMessage.Text = message.Body;
myMessage.Html = message.Body;
var credentials = new NetworkCredential("userName","Password");
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
if (transportWeb != null)
{
return transportWeb.DeliverAsync(myMessage);
}
else
{
return Task.FromResult(0);
}
}
}
At the end you need to register this class Identity in your user manager configurator add following lines:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// some code here
manager.EmailService = new EmailService();
}
See Account Confirmation and Password Recovery with ASP.NET Identity (C#) as a step by step tutorial.
Having trouble update users in AD
My Model:
public class UserModel
{
....
[ScaffoldColumn(false)]
[DisplayName("Fødselsdag")]
[DataType(DataType.Date)]
[NotMapped]
public DateTime extensionAttribute1_date
{
get
{
try
{
return DateTime.Parse(extensionAttribute1);
}
catch (Exception e)
{
return new DateTime();
}
}
set { }
}
}
My Controller:
[HttpPost]
public ActionResult Edit(string sAMAccountName, FormCollection collection, UserModel data)
{
if (ModelState.IsValid)
{
var config = new LdapConfiguration();
config.ConfigureFactory("domain.local").AuthenticateAs(new NetworkCredential("xxxx", "xxxxx"));
using (var context = new DirectoryContext(config))
{
var user = context.Query(new UserModel(), "OU=users,OU=xxx,DC=xxx,DC=dk", "User").FirstOrDefault(d => d.sAMAccountName == sAMAccountName);
if (user == null) return RedirectToAction("Index");
user.title = data.title;
user.mobile = data.mobile;
user.homePhone = data.homePhone;
user.streetAddress = data.streetAddress;
user.postalCode = data.postalCode;
user.l = data.l;
user.department = data.department;
user.physicalDeliveryOfficeName = data.physicalDeliveryOfficeName;
user.extensionAttribute1 = data.extensionAttribute1_date.ToLongDateString();
context.Update(user);
}
return RedirectToAction("Index");
}
return View();
}
When i submit to Edit Action i results in an error:
The requested attribute does not exist.
If i remove extensionAttribute1_date from the model i updates fine.
How do i exclude my calculated attributes from the update?
I have other attributes in the model such as Age which is calculated! Is this the wrong procedure for this?
/Michael