如何在我的 Android 应用程序中使用 ASP.NET Identity 网站登录? [英] How can I use an ASP.NET Identity website login with my Android App?

查看:18
本文介绍了如何在我的 Android 应用程序中使用 ASP.NET Identity 网站登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Core Web 应用程序.用户可以登录,它使用身份.

I have a ASP.NET Core web application. Users can login, it uses Identity.

我现在正在使用 Xamarin 构建一个 Android 应用程序,它将提供网站的一个非常缩小的部分 - 从库存中添加/删除产品.

I am now building an Android app with Xamarin which will provide a very scaled down part of the site - adding/removing products from the inventory.

这是登录操作:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {

        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync    (model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
            if (result.Succeeded)
            {  
              var user = await UserManager.FindByNameAsync( model.Email );
                if ( !user.IsApproved ) {
                    await _signInManager.SignOutAsync();
                    _logger.LogWarning(2, "User account not approved.");
                    return RedirectToAction("NotApproved");
                }

                AddAutoLogoutCookie();

                _logger.LogInformation(1, "User logged in.");
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction("VerifyCode", new { Provider = AppSettings.GoogleAuthenticatorProviderName, ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, _localizer["Incorrect creds"]);
                return View(model);
            }
        }

那么,我可以使用它来让用户登录 Xamarin 应用程序吗?我将如何粗略地处理这个问题?谢谢.

So, can I use this to log users into the Xamarin app? How would I approach this roughly? Thanks.

推荐答案

你的问题很广泛,但我会尽力帮助.如果您有一个网站和一个移动应用程序访问相同的数据库并使用相同的业务逻辑,我建议您创建一个 API,您的 API 应该处理身份验证和访问您的数据层并执行 CRUD 操作.它不在乎消耗它的是什么(移动应用程序或网站).

Your question is very broad but I will try help. If you have a website and a mobile application accessing the same database and using the same business logic I would recommend creating an API, your API should handle authentication and access to your Data layer and perform CRUD operations. It does not care what consumes it (a mobile app, or a website).

您的网站和移动应用将向此 API 发送请求,API 会做出相应的响应.要处理授权,您发送登录信息,API 将返回 Json Web 令牌或 cookie(取决于您使用的内容),对于后续请求,您将随请求发送此令牌.

Your website and Mobile app will send requests to to this API and the API responds accordingly. to handle authorization you send a login and the API will return a Json Web token or cookie (depending on what you are using) and for subsequent requests you send this token with the request.

使用可移植类库 Xamarin 是处理 API 消耗的好地方,因为它可以在 ios 和 android 上重用.

Using Xamarin a portable class library is a good place to handle consumption of the API as it can be reused on ios and android.

如果您使用 Json Web 令牌,您的 Xamarin 请求可能是什么样子的示例.

An example of what your Xamarin request could look like if you are using Json Web Tokens.

public async Task<HttpStatusCode> LoginAsync(CredentialModel credentialModel)
    {
        var uri = new Uri(UrlResourceNames.LoginUrl);
        return await SendCredentialsAsync(credentialModel, uri);
    }
    private async Task<HttpStatusCode> SendCredentialsAsync(CredentialModel credentialModel, Uri uri)
    {
        var jsonProduct = JsonConvert.SerializeObject(credentialModel);
        var httpContent = new StringContent(jsonProduct, Encoding.UTF8, "application/json");
        var response = await _apiConnecter.PostRequest(uri, httpContent);

        if (!response.IsSuccessStatusCode)
            return response.StatusCode;
        string responseJson = await response.Content.ReadAsStringAsync();
        var tokenModel = JsonConvert.DeserializeObject<TokenModel>(responseJson);
        Settings.JwtToken = tokenModel.Token;
        Settings.JwtExpirationDate = tokenModel.Experation;
        return response.StatusCode;
    }

然后是您的 APIConnector,它可以处理对 API 的所有 CRUD 请求.在此示例中,APIConnector 检查是否存在 Json Web 令牌,如果存在,则将令牌与所有请求一起发送(因为在此示例中,除登录和注册之外的所有请求都需要授权),然后 API 验证令牌.

Then your APIConnector which can handle all CRUD requests to the API. In this example the APIConnector checks if there is a Json Web Token present and if there is, it sends the token with all requests (since on this example all requests excluding login and registering require authorization) the API then validates the token.

public class APIConnecter
{
    HttpClient _httpClient;
    private string _jwtToken;
    public APIConnecter()
    {
        _httpClient = new HttpClient();
        ISettings _appSettings;

        _appSettings = _appSettings = CrossSettings.Current;
        _jwtToken = Settings.JwtToken;
        if(!String.IsNullOrEmpty(_jwtToken))
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", _jwtToken);
    }
    public async Task<HttpResponseMessage> GetRequest(Uri uri)
    {      
        var response = await _httpClient.GetAsync(uri);
        return response;
    }
    public async Task<HttpResponseMessage> DeleteRequest(Uri uri)
    {
        var response = await _httpClient.DeleteAsync(uri);
        return response;
    }
    public async Task<HttpResponseMessage> PostRequest(Uri uri, HttpContent content)
    {
        var response = await _httpClient.PostAsync(uri, content);
        return response;
    }
    public async Task<HttpResponseMessage> PutRequest(Uri uri, HttpContent content)
    {
        var response = await _httpClient.PutAsync(uri, content);
        return response; 
    }
}

您在 api 上的登录看起来像这样

Your Login on your api would look something like this

public async Task<IActionResult> Login([FromBody] CredentialModel credentialModel)
    {
        var user = await _userManager.FindByEmailAsync(credentialModel.Email);
        if (user == null)
            return NotFound();
        if (_hasher.VerifyHashedPassword(user, user.PasswordHash, credentialModel.Password) != PasswordVerificationResult.Success)
            return Unauthorized();

        var token = CreateToken(user);
        if (token == null)
            return StatusCode(500, "A problem happened while handling your request");
        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token),
            experation = token.ValidTo
        });
    }

这篇关于如何在我的 Android 应用程序中使用 ASP.NET Identity 网站登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆