Authentication bearer Xamarin

Asked

Viewed 234 times

0

Guys, I’m a beginner in Xamarin and I have a doubt about authentication in an API, when I am consuming via C# or Angularjs for example I can inform in the url the type of authentication (token saved in a session) I got in bearer. In Xamarin Forms I did not understand exactly how I would do this, because I tried to create with sesson and even then it didn’t work, I already searched videos in Outube and I couldn’t find on, I may be looking in the wrong way and my doubt may even seem ridiculous to those who already know, but.. I’m not even able to do that, can anyone help how I can to consume an API and authenticate get calls with authentication ?

1 answer

2

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

First I create a folder Helpers in the project PCL and inside 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, with it I create generic methods where I need to pass only the URL’s I want to make the request. In these methods I call the Settings.TokenSettings containing the token user’s ;

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/"); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.