OAuth 2 Owin not working StackExchange.Redis SessionState - asp.net-mvc

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

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.

How Request.IsAuthenticated work in mvc4 exactly

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!

Does i need to apply Sessions in ASP.NET for log in/log out if im using SimpleMembership in MVC?

I am new to web development so, do i need to implement sessions while i am using SimpleMembership
as i was having problem with back button after logs out. It goes to the previous page instead of login. So I added code below in global.ascx. It works perfect now!!
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
So my query is, can i run my application without sessions in which there is Authentication of users i.e. there are user accounts and login and logout functionality is there.
You can login and logout by using default SimpleMembership functions:
For Login:
bool success = WebSecurity.Login(form["username"], form["password"], false);
For Logout:
WebSecurity.Logout();
For details refer MSDN link here

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");
}

ASP.NET MVC 4 problems with Facebook authentication

In my ASP.NET MVC 4 I use external authentication providers - Facebook and Google. I created the app with Internet template and did not change code inside Account controller.
Now some of my users started to complain they cannot register via Facebook, while other users use it without any problems.
I succeeded to simulate the problem. With my Facebook profile everything works OK. When I created a new profile on Facebook, I experience the same problem.
In AccountController, ExternalLoginCallback method:
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
result.IsSuccessFull returns true for my profile, but false for the new Facebook profile I created.
Any ideas what could be wrong?
Thanks a lot
I forgot to switch off the sandbox mode...

Resources