How Request.IsAuthenticated work in mvc4 exactly - asp.net-mvc

I made 2 MVC Project that use login form before start
I use this code for login
public ActionResult Login(AccountLog Usr)
{
AccountLog personindatabase = db.AccountLogs.FirstOrDefault(m => m.Usercode == Usr.Usercode);
FormsAuthentication.SetAuthCookie(personindatabase.UserName, true);
ViewBag.id = personindatabase.Usersid;
return RedirectToAction("Main", "Main");}
when I run program at I check first if(Request.IsAuthenticated) if true return view if else redirect to login page as this
public ActionResult Main()
{
if (Request.IsAuthenticated)
{
return View();
}
return RedirectToAction("Login", "Account");
}
it worked fine but I noticed that if I run the first program and made success login and close it not made logout and run the second program that not logged yet it open as it logged person this mean if i made login from the first one and open the second it will open fine and vise versa how can i differentiate between 2 project login how can i made alternative for Request.IsAuthenticated if any thing in question don't clear leave comment to clear it to be able to help me

From what you just described you are trying to login to the same application using the same browser session in two different tabs without logging out the first user.
When a login is a success an Authentication Cookie is set in the browser. This cookie is sent to the server each time so that the server can validate the user.
As you are trying to login ( or expect to login) into the second tab using another account, you already see the first user logged in as the Authentication Cookie for that account still persisted in the browser. The Authentication cookie will expire only when the user logs off.
So you can either.
Test two accounts using two different browsers(e.g. Chrome and Firefox)
Log off the first account before trying to login using another account in the same browser.
Hope that helps!

Related

Identity server 4 with asp.net identity registration

I want to know, how to correctly implement user registration in my identity server with asp net identity with redirection to login page after registration and then redirection to callback URL after login with registered account.
I followed Identity Server 4 quickstart tutorial and as far i created my own mvc identity server with asp.net identity. Now i want to add some registration so i created RegistrationController with Registration form and added Register button to login form.
I have an asp.net mvc application which require authentication. When user runs main page, he is automatically redirected to my identity server login page. User clicks register button, fills required information and clicks register button to confirm registration. Registration controller creates a new account and stores it in database using account manager.
This is part i am missing:
After successful registration i want an user to be redirected back to login page and when user logs in he should be redirected back to the web application and authenticated.
I am new to the web terminology especially mvc. Can you recommend me please some documentation where i can learn more to solve this problem ?
I have faced similar problem in one of my projects and basically the way we achieved this desired behavior was to retain the original connect/authorize query parameters throughout the registration flow and then at the end redirect the user back to the connect/authorize url with the original query parameters.
All worked out of the box from that point on since it had the original callback uri to the client that initiated the OAuth flow in the first place.
Thanks Vidmantas Blazevicius tip i found solution. When user clicks register i redirect him to the register page with return URL as query parameter. When user confirms or cancels registration he is redirected back to AccountContoller.Login(string returnUrl) action. Then when user logs in, he is successfully redirected back to original site.
This is the AccountControler.Register action when user clicks register in login page:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(LoginInputModel model)
=> RedirectToAction("register", "registration", new { returnUrl = model.ReturnUrl });
This calls RegistrationController.Register to show registration form:
[HttpGet]
[Route("register")]
public ViewResult Register([FromQuery]string returnUrl)
=> View("Views/Account/Registration.cshtml", new UserRegistrationViewModel(returnUrl));
The RegistrationController.Cancel action is executed when user clicks cancel in registration page:
[HttpPost]
[Route("cancel")]
public IActionResult Cancel(UserRegistrationViewModel viewModel)
=> RedirectToAction("login", "account", new { returnUrl = viewModel.ReturnUrl });
In registration form use return URL property of view model like this #Html.HiddenFor(x => x.ReturnUrl) otherwise it will be not set in Cancel postback.

Two Step Verification in ASP.Net MVC using Web Security

I implemented two step verification in a ASP.Net MVC page which uses Web Security by doing the following logic:
1) When the user login's first time and when clicks Next in the Login page,he is validated-
if (Membership.ValidateUser(model.UserName, model.Password))
{
......// Encrypt the password and storing it in a session
......// Then redirect to step 2 verification page...
}
and he gets redirected to 2nd step verification page where he would be asked to enter a security Q. If he gets it correct then a new cookie(Cookie2) is created,
and the user is logged in using-
.......//Decrypt the password
_webSecurity.Login(username, decryptedpassword, false)
and then he is redirected to his home page.
2) Next time when he tries to login to the app, there is a check to see if the cookie(Cookie2) which is created in the 2nd step is existing or not. If it exists, then he is redirected to the Home page directly and if its not existing then he is again asked to enter security Q.
So if we see the implementation here, i am actually logging the user into the app only if he gets 2nd step verification valid. In order to implement this, i am creating a cookie and storing the password in a session.
Can anyone let me know if we can code this in a better way?I am guessing we can do this without using sessions and cookies.
Any ideas/suggestions are most welcome.
Thanks,
WH

OAuth 2 Owin not working StackExchange.Redis SessionState

Starting with a fresh, new MVC5 Project I hooked up External OAuth Login with Google, Facebook Twitter, Microsoft etc. All is working as expected.
I then added the new ASP.NET Session State Provider for Redis Preview Release and have it working. Yeah!
I soon noticed that attempting to login using any of the OAuth providers no longer works properly. The Google & Facebook login buttons calls the ExternalLoginCallback(string returnUrl) on the Accont controller but goes nowhere. The login page simply refreshes.
The LinkedIn, Twitter, and Microsoft buttons all direct the user to those login pages but when returned back to my application they return to the login page and no user is added to the system.
Commenting out the custom sessionState entry in my web.config returns the external login back to normal.
Considering both frameworks are black-boxes to me I am not sure how to go about geting these two to play together.
this helped me with the exact issue.
http://www.nsilverbullet.net/2014/06/24/tough-mvc-5-owin-external-authentication-issue/
basically:
Must Have Session State? in AccountController modify:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
//Ensure Session has at least one value
Session["EnableExternalAuth"] = true; // <--------- This helped
ViewBag.ReturnUrl = returnUrl;
return View();
}
There seem to be an issue with sessions and external login providers

Logging out from facebook when using MVC 5 OWIN

I have an MVC 5 web app that has facebook authentication set up and working nicely. User clicks "Facebook" on the login page, signs in to Facebook and that authenticates with our web site. If the user logs out, the call to AuthenticationManager.SignOut() logs out of the web site correctly, but if the user then goes back to the login page and clicks "Facebook" again they are immediately signed in without having to sign in to facebook.
So my question is, how do I configure MVC 5 OWIN facebook login so that the user is signed out of facebook when they sign out of the web site, or to put it another way, prevent caching of the authentication for the next sign in. I don't want a users facebook login to be silently cached in case they are sharing a browser with other users.
The only way that I know to do this would be to tie an event to your log out button or link and use the Facebook Javascript SDK to actually perform the Facebook logout for you.
LogOut
<script type="text/javascript">
$(function(){
$("#Logout").on("click", function(e){
if(confirm("This will also log you out of Facebook. Proceed?")){
FB.logout(function(response) {
// Person is now logged out
});
}else{
//do not allow the link to continue and sign our of your site.
//This is optional and allows you to provide options
e.PreventDefault();
}
});
});
</script>
You could actually use the confirm dialog to ask if they want to be signed out of Facebook as well. A confirm would mean yes, a not confirm would mean no, just sign me out of your site. Again, using the SDK and a little bit of control logic should provide the results you need.
You can't. To do so would require being able to access cookies set by facebook.com which is explicitly forbidden for security reasons: you can only access cookies on your own domain. The login with Facebook is separate from your application. The user isn't truly logging into your site. They're logging into Facebook and Facebook is simply verifying the user identity with your site. If you're truly concerned you can put a message on your sign out page reminding them to sign out of Facebook as well.
You could try recreating Facebook's log out code (doing a post to the same action they use with the same data they send). But, I'm almost positive they'll be employing some sort of CSRF protection on that, so it probably won't work.
Saw this thread and wanted to add to it, to help the masses.
In the guidance, "Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on" from Microsoft, it has the following section buried in it:
Logging off your App and Logging in With Another Account
If you log on to your app with Facebook, , and then log out and try to log in again with a different Facebook account (using the same browser), you will be immediately logged in to the previous Facebook account you used. In order to use another account, you need to navigate to Facebook and log out at Facebook. The same rule applies to any other 3rd party authentication provider. Alternatively, you can log in with another account by using a different browser.
So this behavior is by design.
To learn more about OWIN, hear is some good reading:
http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
http://brockallen.com/2014/01/09/a-primer-on-external-login-providers-social-logins-with-owinkatana-authentication-middleware/
Have more links to share, but drats, reputation is not high enough yet. :)
Its been two years and If OpenID Connect is used, then a solution exists as
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
Request.GetOwinContext().Authentication.SignOut();
return Redirect("/");
//AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
//return RedirectToAction("Index", "Home");
}

Where to check for session and trigger login

I am starting a Zend Framework 2 project and I am a little stuck on something simple. I need to trigger the user to get redirected to a login page if they are not logged in using a session variable being present.
My question is, where is the best place to put a function to check to see if the user is logged in and if not send them to an authentication controller to start the login process? Since it needs to be checked all the time, where should it go?
Thanks!
In Controller you can write like this,
This will be trigged on each time it enters Controller before going any other Action
public function init()
{
if (!(Zend_Auth::getInstance()->hasIdentity())) { // if user session not exists
//Redirect to login page
}
}

Resources