Authentication bearer Xamarin

0

I am new to xamarin and I have a question about authentication in an API, when I am consuming via C # or angularJS for example I can enter in the url the type of authentication (token that saved in a session) that I got in bearer. In Xamarin forms I did not understand for sure how I would do it, because I tried to create with sesson and it still did not work, I even searched for videos on youTube and did not find out about it, I may be searching the wrong way and my doubt may even seem ridiculous for those who already More ... I'm not even able to do this, can anyone help me how can I do to consume an API and authenticate get calls with authentication?

    
asked by anonymous 26.03.2018 / 21:15

1 answer

2

It is necessary to save token locally, in the case of Android, this is called SharedPreferences , here is an example of how I do in my applications.

First I create a Helpers folder in the PCL project and inside I create a static class called Settings :

public static class Settings
{
    private static ISettings AppSettings
    {
        get
        {
            return CrossSettings.Current;
        }
    }

    #region Setting Constants

    private const string SETTINGS_USERNAME_KEY = "UserName";
    private const string SETTINGS_EMAIL_KEY = "Email";
    private const string SETTINGS_TOKEN_KEY = "access_token";
    private const string SETTINGS_NICK_NAME_KEY = "NickName";
    private static readonly string SETTINGS_DEFAULT = string.Empty;

    #endregion

    public static string UserNameSettings
    {
        get
        {
            return AppSettings.GetValueOrDefault(SETTINGS_USERNAME_KEY, SETTINGS_DEFAULT);
        }
        set
        {
            AppSettings.AddOrUpdateValue(SETTINGS_USERNAME_KEY, value);
        }
    }

    public static string UserNickNameSettings
    {
        get
        {
            return AppSettings.GetValueOrDefault(SETTINGS_NICK_NAME_KEY, SETTINGS_DEFAULT);
        }
        set
        {
            AppSettings.AddOrUpdateValue(SETTINGS_NICK_NAME_KEY, value);
        }
    }

    public static string EmailSettings
    {
        get
        {
            return AppSettings.GetValueOrDefault(SETTINGS_EMAIL_KEY, SETTINGS_DEFAULT);
        }
        set
        {
            AppSettings.AddOrUpdateValue(SETTINGS_EMAIL_KEY, value);
        }
    }

    public static string TokenSettings
    {
        get
        {
            return AppSettings.GetValueOrDefault(SETTINGS_TOKEN_KEY, SETTINGS_DEFAULT);
        }
        set
        {
            AppSettings.AddOrUpdateValue(SETTINGS_TOKEN_KEY, $"Bearer {value}");
        }
    }
}

After that, in my login method I assign the values to the fields:

public void MeuMetodoDeLogin(){
    Settings.TokenSettings = "Token Bearer";
    Settings.UserNameSettings = "Nome do usuário";
    Settings.UserNickNameSettings = "NickName";
    Settings.EmailSettings = "Email";
}

Then, to make the requests I use the nuget RestSharp package, with it I create generic methods where I need to pass only the URL's that I want to make the request. In these methods I call the Settings.TokenSettings that contains the token of the user;

public class BaseService
{
    protected RestRequest _request;
    protected RestClient _client;
    protected readonly string _urlBase = "http://MyUrl.com.br:1234/api/";

    public virtual async Task<List<TEntity>> GetAllAsync<TEntity>(string url)
    {
        try
        {
            _client = new RestClient(_urlBase);
            _request = new RestRequest(url, Method.GET);
            _request.AddHeader("Authorization", Settings.TokenSettings);
            _request.RequestFormat = DataFormat.Json;
            IRestResponse<List<TEntity>> resposta = await _client.ExecuteTaskAsync<List<TEntity>>(_request);
            var obj = JsonConvert.DeserializeObject<List<TEntity>>(resposta.Content);
            return obj ?? new List<TEntity>();
        }
        catch (System.Exception e)
        {

            return new List<TEntity>();
        }

    }

    public virtual async Task<List<TEntity>> GetAllByIdAsync<TEntity>(int id, string url)
    {
        try
        {
            _client = new RestClient(_urlBase);
            _request = new RestRequest(url, Method.GET);
            _request.AddHeader("Authorization", Settings.TokenSettings);
            _request.AddParameter("id", id);
            _request.RequestFormat = DataFormat.Json;
            IRestResponse<List<TEntity>> resposta = await _client.ExecuteTaskAsync<List<TEntity>>(_request);
            var obj = JsonConvert.DeserializeObject<List<TEntity>>(resposta.Content);
            return obj ?? new List<TEntity>();
        }
        catch (System.Exception)
        {
            return new List<TEntity>();
        }

    }

    public virtual async Task<TEntity> GetByIdAsync<TEntity>(int id, string url)
    {
        try
        {
            _client = new RestClient(_urlBase);
            _request = new RestRequest(url, Method.GET);
            _request.AddHeader("Authorization", Settings.TokenSettings);
            _request.AddParameter("id", id);
            _request.RequestFormat = DataFormat.Json;
            IRestResponse response = await _client.ExecuteTaskAsync(_request);
            var obj = JsonConvert.DeserializeObject<TEntity>(response.Content);
            if (obj == null)
                return default(TEntity);
            else
                return obj;
        }
        catch (System.Exception)
        {

            return default(TEntity);
        }

    }

    public virtual async Task<TEntity> GetAsync<TEntity>(string url)
    {
        try
        {
            _client = new RestClient(_urlBase);
            _request = new RestRequest(url, Method.GET);
            _request.AddHeader("Authorization", Settings.TokenSettings);
            _request.RequestFormat = DataFormat.Json;
            IRestResponse response = await _client.ExecuteTaskAsync(_request);
            var obj = JsonConvert.DeserializeObject<TEntity>(response.Content);
            if (obj == null)
                return default(TEntity);
            else
                return obj;
        }
        catch (System.Exception)
        {

            return default(TEntity);
        }

    }
}

Finally, to call the method it will be necessary to instantiate the class BaseService and call 1 of the methods:

List<MinhaClasse> minhasClasses = GetAllAsync<MinhaClasse>("GetMinhaUrl/"); 
    
26.03.2018 / 22:52