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

查看:72
本文介绍了如何在我的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天全站免登陆