Where to store Bearer Token in MVC from Web API

后端 未结 2 509
故里飘歌
故里飘歌 2020-12-12 18:12

Scenario

I have an ASP.NET Web API that uses the OAuth Password Flow to provide Bearer Tokens to gain access to its resources.

I\'m now in t

2条回答
  •  甜味超标
    2020-12-12 19:06

    Since you have mentioned you are using HttpClient(). I did a similar thing using HttpClient()-

    Get token-

        static Dictionary GetTokenDetails(string userName, string password)
        {
            Dictionary tokenDetails = null;
            try
            {
                using (var client = new HttpClient())
                {
                    var login = new Dictionary
                       {
                           {"grant_type", "password"},
                           {"username", userName},
                           {"password", password},
                       };
    
                    var resp = client.PostAsync("http://localhost:61086/token", new FormUrlEncodedContent(login));
                    resp.Wait(TimeSpan.FromSeconds(10));
    
                    if (resp.IsCompleted)
                    {
                        if (resp.Result.Content.ReadAsStringAsync().Result.Contains("access_token"))
                        {
                            tokenDetails = JsonConvert.DeserializeObject>(resp.Result.Content.ReadAsStringAsync().Result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
    
            }
            return tokenDetails;
        }
    

    Use the token to Post data

    static string PostData(string token, List> lsPostContent)
    {
        string response = String.Empty;
        try
        {
            using (var client = new HttpClient())
            {
                FormUrlEncodedContent cont = new FormUrlEncodedContent(lsPostContent);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                var resp = client.PostAsync("https://localhost:61086/api//", cont);
    
                resp.Wait(TimeSpan.FromSeconds(10));
    
                if (resp.IsCompleted)
                {
                    if (resp.Result.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine("Authorization failed. Token expired or invalid.");
                    }
                    else
                    {
                        response = resp.Result.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(response);
                    }
                }
            }
        }
        catch (Exception ex)
        {
    
        }
        return response;
    }
    

    Even if you store the Bearer token in HttpContext, you will need to take care of the token expiry time which is set in the Web API. Validating the existence of token just in the session won't help since the old token will be invalid after the expiry time.

提交回复
热议问题