如何从Web API全局存储和访问令牌?

时间:2019-07-10 21:50:07

标签: c# asp.net asp.net-core asp.net-core-mvc token

我正在使用一个仪表板Web应用程序,该应用程序使用grant_type=client_credentials来获取Bearer Token以获得对资源的访问权限。

计划是让MVC控制器代表客户端浏览器对API进行调用。

来自浏览器的ajax请求将命中MVC控制器,然后进行API调用。然后将结果作为JSON反馈给客户端,并在react中进行处理。

客户端永远不应直接与API通信,也不需要登录即可查看仪表板。

应用程序首次加载时,会使用存储在appsettings.json中的客户端凭据向服务器请求令牌。我可以获取令牌,但不知道在哪里存储和访问令牌。我需要全局访问此令牌,以便在20分钟左右后可以将refresh_token请求发送到服务器,并在随后的所有对该API的调用中使用它以获取数据。

我可以将其存储在HttpContext中并从那里使用吗?

目前,我正在请求令牌,如下所示:

public class TokensController : ControllerBase
    {
        public IConfiguration Configuration { get; }

        public TokensController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // Get Token
        public static async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
        {
            HttpClient client = new HttpClient();
            FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
            HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
                throw new ApplicationException(message);
            }

            string responseString = await response.Content.ReadAsStringAsync();
            Token token = JsonConvert.DeserializeObject<Token>(responseString);

            return token;
        }

        public IActionResult GetAccessToken()
        {

            Dictionary<string, string> authenticationCredentials_np = Configuration.GetSection("SomeEnvironment:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
            Token token_np = GetToken(new Uri(Configuration["SomeEnvironment:URL"]), authenticationCredentials_np).Result;

            return Ok(token_np);
        }

    }

有什么建议/想法吗?

0 个答案:

没有答案
相关问题