Identity server 4 with asp.net identity registration - asp.net-mvc

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.

Related

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!

Retain query string parameters after authorization fails in MVC

I have a task in which I have to make sure to do a particular action (open a popup) on the basis of some url parameters in the query string when a user clicks a link from an email, but suppose the user is not logged then the authorization fails as the action I am redirecting the user to is has the authorize attribute,
I show a page here saying authorization has failed and then there is a link through which the user can log in and get redirected to her landing page.
Unfortunately the URL parameters get lost.
I have them in the filtercontext when function HandleUnauthorizedRequest gets hit, how do I flow this URL after login.
You need to flow the information of the original intent or destination in the login screen when the user is not logged in.
One standard way to do this would be to include the information in the query string e.g. http://blah.com/login?continue=<url encoded original url>. When the user successfully logs in, simply see if the query string had a value and then redirect the user there, if not just do the default action of login.

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

Asp.Net MVC: Current User changes after Registration of a new user

I am having a problem with my asp.net application. I am using the default Register.aspx to register a new user. After the user have been successfully created i am redirected to a new page that informs me of the success. When i try to navigate to a different page the current user changes to the one i just created. I want to keep the current user. What am i missing?
Thanks
Remove the following line from your Register action in the Account controller upon successful registration:
FormsAuthentication.SetAuthCookie(model.UserName, false);
This is what changes the user by emitting a new authentication cookie in the response with this username.

Resources