c# - How to get user information after successful authentication? -
the goal
get user information after successful authentication.
the problem
take in following fragment of code:
[acceptverbs(httpverbs.post)] [validateantiforgerytoken] [allowanonymous] public actionresult authenticate(user usermodel) { if (modelstate.isvalid) { if (usermodel.isvalid(usermodel.email, usermodel.password)) { formsauthentication .setauthcookie(usermodel.email, usermodel.remember); return redirecttoaction("index", "manager"); } else { modelstate.addmodelerror("", "login data incorrect!"); } } return redirecttoaction("index"); }
as can see, normal authentication's controller. need simple: if statement usermodel.isvalid
true, how can user information based on email sent server usermodel.email
?
maybe store email on session , in index
method call method (user) information passing through parameter email inhabiting session? (i think isn't best way because if cookie exist , session not, there problem here.)
code spotlight
to information of user, i'm using simple method: user.invoke((string) useremail)
.
knowledge improvement
i'm logging in on website email
, password
various applications of world do. email
user enters, i'm attempting information database. ask: best way this? maybe isn't better firstly id of user email , select information?
what tried
in authenticate
method (the same passed before), implemented following code:
[...] public actionresult authenticate(user usermodel) [...] if (usermodel.isvalid(usermodel, usermodel.password)) { formsauthentication .setauthcookie(usermodel.email, usermodel.remember); session["useremail"] = usermodel.email; // <-- pay attention return redirecttoaction("index", "manager"); } [...] }
and then, in index
method:
public actionresult index() { if(request.isauthenticated()) { userprofile user = user.invoke(session["useremail"])); return view(user); } else { return view(); } }
but said, if cookie flags user logged in alive , session not, there problem right here — kind of concept conflict (cookie vs. session).
what can do?
the accepted answer (from discussion op) : straightforward way of retrieving user name set forms authentication module use
httpcontext.current.user.identity.name
or just
this.user.identity.name
in controller.
Comments
Post a Comment