Forum Xamarin.Android

Asp net get token

DimChrisDimChris USMember ✭✭✭✭

I' am using method below for taking token.

 private static string AccessToken ;
 private static string TokenType ;

 public async static Task<bool> GetToken(string username, string password)
    var token = new FormUrlEncodedContent(new[]
         new KeyValuePair<string, string>("username", username),
         new KeyValuePair<string, string>("password", password),
         new KeyValuePair<string, string>("grant_type", "password")
    using (var client = new HttpClient())
        client.Timeout = TimeSpan.FromMilliseconds(20000);
        var response = await client.PostAsync(ServerTokenString, token);

        if (response.IsSuccessStatusCode)
            string content = await response.Content.ReadAsStringAsync();
            var tokens = content.Split('"');
            AccessToken = tokens[3];
            TokenType = tokens[7];
            return true;
        return false;

After this i am using Token for making requests on server.
But i have some question around this.
First question: I have set token be expired after 1 hour. So when i am making a request after one hour i am getting error: "Message": "Authorization has been denied for this request."
In this case i need to re-run my first routine for getting new token?(Re send email and password?) Or there is any mechanism which is refreshing my token if i am already log in?

Second Question: Each time i making log out from my application i need to delete my acesstoken or there is no need for this, cause after one hour it will be removed automatically?


  • mdecoomdecoo Member ✭✭
    edited December 2018

    As per your questions:
    1: You will need to check the expiring of the token and login again to keep it safe.
    If username and password are saved you can use the logincommand to re-authenticate

    if (Settings.AccessTokenExpirationDate < DateTime.UtcNow.AddHours(1))
                            var loginViewModel = new LoginViewModel();

    2: It safe to leave it, but better to delete the token when you logout. (I'm deleting the token)

  • DimChrisDimChris USMember ✭✭✭✭
    edited December 2018

    Thank you very useful answer. One last question, why i need to logout? If token will expired isn't the same?
    Also what if client have different hour from server?

Sign In or Register to comment.