After redirect from one controller to another controller Not able to receive User.Identity.name value in mvc. how to solve this Issue? - asp.net-mvc-5

I am able to get the User.Identity.Name value from Login Controller after redirect to Dashboard(another Controller) i am not able to receive the User.Identity.Name value (i am getting Null value)
below is my code:-
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return Redirect("/Dashboard");
}
After return Redirect("/Dashboard"); Getting null value in Dashbord Controller.
Below is my Dashborad controller code :-
public ActionResult Index()
{
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return View();
}

Related

query string param is not url-encoded inside asp.net mvc action

I'm calling ResetPassword action from an Email (ASP.NET MVC 5).
http://localhost:34162/Account/ResetPassword?code=BwEA181bAECFMcn1vwPdrctS/wcyncKPxGT9Zx1tDuPwKGpe9H1W7LI3Zm9fM+3aA5Fok5GhLPBHqbtiGfpL8Cmdx7RNC6RJ7d6t9ZgFBwgwYk3zssU1Nh64PWHJAabVG9Wv9VWDNdj+Fz0UA712XA==
This is the address in my Browser.
However, in debug I receive this string in the ResetPassword Action:
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
The 'code' is:
BwEA181bAECFMcn1vwPdrctS/wcyncKPxGT9Zx1tDuPwKGpe9H1W7LI3Zm9fM 3aA5Fok5GhLPBHqbtiGfpL8Cmdx7RNC6RJ7d6t9ZgFBwgwYk3zssU1Nh64PWHJAabVG9Wv9VWDNdj Fz0UA712XA==
i.e., it is not url-encoded and of course password is not reset with invalid token message.
What can I do for getting the right string in the Action?
You can encode the string in the following way:
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
code = Server.HtmlEncode(code);
}
Fore more information on how to encode you can look at
https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx
I still don't know what was the problem. Looks like it shouldn't have worked in the first place. I wish I knew why Microsoft feel the need to use tokens with slashes and pluses.
Anyway, I just Base64 encoded and decoded the token as follows:
before sending the Email to the user:
...
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
code = CommonFuncs.Base64Encode(code);
EmailsBL.PasswordResetEmail(model.Email, code); <-- emailing the link for password rest to the user
And then when receiving:
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
/////////////////////////////////////////////////////////////////////
// NOTE: if email is not CONFIRMED then reset password silently fails
////////////////////////////////////////////////////////////////////
if (!ModelState.IsValid)
{
return View(model);
}
model.Code = CommonFuncs.Base64Decode(model.Code);
i.e., decoding the token.
This following is just for completeness:
public static string Base64Encode(string plainText)
{
string base64string = null;
if (plainText != null)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
base64string = System.Convert.ToBase64String(plainTextBytes);
}
return base64string;
}
public static string Base64Decode(string base64EncodedData)
{
string decodedBase64String = null;
if (base64EncodedData != null)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
decodedBase64String = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
return decodedBase64String;
}

Getting UserId from MVC using WebMetrix

I'm using bellow login method to login in a MVC 5 application.
What I want to do is get the id of the user that is currently logged.
I tried to use these 2 methods:
// 1
// This one raise an exception:
Guid loggedUser = (Guid)Membership.GetUser().ProviderUserKey;
Additional information: Object reference not set to an instance of an
object.
// 2
// sets loggedUser variable to null
loggedUser = User.Identity.GetUserId();
// Login Method within Controller
public ActionResult Login(Login logindata, string ReturnUrl)
{
if (ModelState.IsValid)
{
if (WebSecurity.Login(logindata.Username, logindata.Password))
{
if (ReturnUrl != null)
{
return Redirect(ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Sorry the username or password is invalid ");
return View(logindata);
}
My question is what I'm doing wrong and if it's possible to get the logged user id like this???
Thanks
I used this method and worked:
WebSecurity.GetUserId("loggedUser")

AttributeRouting: Multiple routes based on user roles

thank you for your reply,
i added BeginExecuteCore in base controller like this
`public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//string email = string.Empty;
dbEntities dbcontext = new dbEntities();
var userRoleName = (from n in dbcontext.VAgentClientEmails where n.Email == User.Identity.Name select n.Role).FirstOrDefault();
if (userRoleName == "SuperAdmin")
RouteData.Values["role"] = userRoleName;
else
RouteData.Values["role"] = "";
return base.BeginExecuteCore(callback, state);
}`
and i have given in home controller like this
[Route("~/{role}/SavedSearch/Index")]
public ActionResult Index()
{
...
}
its working for admin/savedsearch/index
and also if i give fjsdfk/savedsearch/index its working
in the above case it should not work..
and in else case i dont want role
do i need to do any changes?

Account Controller error

Hello guys I have a problem in the Account Controllers wanted to add a method for viewing jobs for employees, but now it is giving me an error "Not all code paths return a value"
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
}
Your method's return type is ActionResult
public ActionResult ViewAssignJob()
{
}
In these type of method you generally return View() or return View(viewmodel).
If you don't want to return view for some debugging purpose, you could also return content("hello world") this will result to Hello world in a blank page
Return View() from Actionresult and your error will gone.
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(); // or // return View(Model);
}
hey you just forgot one important line as your error suggest, just put a return statement in your method so that it returns what you want. after this I am sure you will not be experiencing any problem.
here is how your code should look like!
public ActionResult ViewAssignJob()
{
var userId = User.Identity.GetUserId();
var jobs = _jobService.GetEmployeeJobs(userId);
return View(jobs);
}

Get Resource based on currently authenticated user

If I have an operation using ServiceStack such as GetOrders:
[Route("/orders")]
public class GetOrders : IReturn<List<Order>> { }
I then use this in a service:
[Authenticate]
public class OrdersService : Service
{
public object Get(GetOrders request)
{
var dbOrders = Db.Select<Order>().ToList();
// What I want is to only get orders of the user making the request
// var dbOrders = Db.Select<Order>().Where(x=>x.UserId == ??).ToList();
return dbOrders;
}
}
Assuming my Order entity has a property called UserId, how do I get access to the currently logged in user where I can then map to the UserId and select only those orders from my database?
You can get access to your typed UserSession via the SessionAs<T> method, e.g:
[Authenticate]
public class OrdersService : Service
{
public object Get(GetOrders request)
{
var userSession = base.SessionAs<AuthUserSession>();
var userId = int.Parse(userSession.UserAuthId);
var dbOrders = Db.Select<Order>(x => x.UserId == userId);
return dbOrders;
}
}

Resources