Use MVC AccountController to login in Android App

Viewed 961

I'm working on a mobile application (in Android) which has to connect to an Azure database (this database is also used by the web version of the app). I succeeded to send POST/PUT/GET requests to the webservice API, using HttpURLConnection and now I'm trying to login in the app using the MVC AccountController.
Here is the MVC AccountController method I'm trying to call:

    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {   
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation(1, "User logged in.");
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Here is the LoginViewModel structure(first parameter of the Login method)

public class LoginViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

And here is what I've already tried, but I received: Bad request

public static String apiURL = "http://mysite/account/login";

public static String logIn() {
    HttpURLConnection connection = null;

    try {
        URL url = new URL(apiURL);
        JSONObject postDataParams = new JSONObject();
        postDataParams.put("Email", "test@yahoo.com");
        postDataParams.put("Password", "mypass");
        postDataParams.put("RememberMe", true);

        JSONObject finalJson = new JSONObject();
        finalJson.put("model", postDataParams);
        finalJson.put("returnUrl", "");

        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(15000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/json");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(finalJson.toString());
        out.close();
        System.out.println(finalJson.toString());
        StringBuilder sb = new StringBuilder();
        sb.append("");
        int HttpResult = connection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            System.out.println("" + sb.toString());

        } else {
            System.out.println(connection.getResponseMessage());
        }
        return sb.toString();
    } catch (Exception e) {
        return new String("Exception: " + e.getMessage());
    } finally {
        connection.disconnect();
    }
}

Does anyone have an idea of what should I do? Thank you!

1 Answers
Related