Andy Donegan
Andy Donegan

Reputation: 915

Apache Cordova connecting to Asp.net Web Application in MVC5

I currently have a an ASP.NET Web Application using MVC 5 with asp.net-identify and user roles enabled.

The site is working well and handling data requests to our database tables and blob storage.

We have a mobile app written in Apache Cordova Visual Studio 2015 which implements Bluetooth LE all working as expected.

I have learnt a huge amount to get to just this stage, but now I have hit a brick wall and appreciate some solid advice/guidance.

I'm am trying to initially log my users in to the web site from my Mobile App automatically and re-direct them to a specific page.

My MVC site code for logging in is below.

    //
    // GET: /Account/AppLogin
    [AllowAnonymous]
    public ActionResult AppLogin()
    {
        ViewBag.ReturnUrl = "not used";
        return View();
    }

    //
    // POST: /Account/AppLogin
    [HttpPost]
    [AllowAnonymous]
    //[ValidateAntiForgeryToken]  <-- Commented out to try to gain access from Cordova.
    public async Task<ActionResult> AppLogin(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // Require the user to have a confirmed email before they can log on.
        // var user = await UserManager.FindByNameAsync(model.Email);
        var user = UserManager.Find(model.Email, model.Password);
        if (user != null)
        {
            if (!await UserManager.IsEmailConfirmedAsync(user.Id))
            {
                string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Account Registration - Confirm your account-Resend");

                // Uncomment to debug locally  
                // ViewBag.Link = callbackUrl;
                ViewBag.errorMessage = "You must have a confirmed email to log on. "
                                     + "The confirmation email has been resent to your email account.";
                return View("Error");
            }
            var currentUser = UserManager.FindByName(model.Email);
            bool roleresult = UserManager.IsInRole(currentUser.Id, "Customer");
            if (roleresult == false)
            {
                ViewBag.errorMessage = "You do not have Customer Account Accesss for this site. "
                                        + "Please contact the Support Team.";
                return View("Error");
            }
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return AppRedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

    private ActionResult AppRedirectToLocal(string returnUrl)
    {
        return RedirectToAction("Index", "Customer");
    }

My View Code is below.

    <section id="loginForm">
        @using (Html.BeginForm("AppLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <div class="checkbox">
                        @Html.LabelFor(m => m.RememberMe)<text> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</text>
                        @Html.CheckBoxFor(m => m.RememberMe)

                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Log In</button>
                </div>
            </div>
            <p>
                @Html.ActionLink("Register as a new user", "Register")
            </p>

                <p>
                    @Html.ActionLink("Forgot your password?", "ForgotPassword")
                </p>
        }
    </section>

My Apache Cordova code is simple below.

     <form action="https://nameofmywebsite.azurewebsites.net/Account/AppLogin/" class="form-horizontal" method="post" role="form">
                <input name="__RequestVerificationToken" type="hidden" value="" />   <!-- Left this code in but do not think it is required.  -->
         <hr />

                        <input id="Email" name="Email" type="text" value="[email protected]" />

                        <input id="Password" name="Password" type="password" value="Andy.1234" />

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            <label for="RememberMe">Remember me?</label><text> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</text>
                            <input data-val="true" data-val-required="The Remember me? field is required." id="RememberMe" name="RememberMe" type="checkbox" value="true" />

                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Log In</button>
                    </div>
                </div>
                <p>
                    <a href="/Account/Register">Register as a new user</a>
                </p>
                <p>
                    <a href="/Account/ForgotPassword">Forgot your password?</a>
                </p>
            </form>

I can now see the username and password passed to the form and filled in correctly.

The key problem, I want to open the form Action within a cordova.InAppBrowser.open session as I do not have access to the browser controls opening within the app.

Also I would greatly appreciate anybody advising me on how to write a web api to auto log in to my MVC site and then potentially get authorisation and pass data backwards to my mobile app ?

I know the scope of this question is broad my apologies, I just need a foot hold to nudge me in the correct direction.

I have looked in to Azure Mobile Services and this seems like a good way to go, but I can not find any reference to help me authorise my users using the existing process within my MVC site.

Many thanks in advance for suggestions/links or slaps in the correct direction.

Upvotes: 0

Views: 719

Answers (1)

user3255670
user3255670

Reputation:

@Andy,
this is a common misunderstanding with Cordova/Phonegap. While you are using a webview (library) to do the rendering, there is NO need to use a CGI. You can infact do the same with an AJAX call or a REST API. This means your MVC code, while pretty, is a complete waste. You can do everything you need with Javascript and AJAX.

I would suggest you learn about AJAX, because while Javascript is foreign to most programmers, once they understand it, they get it.

Microsoft should have something equivalent to this
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

One last thing, the AJAX system is Asynchronous, NOT synchronous. This means the system is event-driven and not linear. If you need clarity on Asynchronous, please ask.

Best of Luck

Upvotes: 1

Related Questions