Azure Active Directory - MVC application best practices to store the access token

坚强是说给别人听的谎言 提交于 2019-12-05 12:34:14

When you are retrieving tokens through Adal it is caching it in NaiveCache object.

Code to retrieve token withing StartUp class:

  AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, "Your API Resource ID");
                            string kdAccessToken = kdAPiresult.AccessToken;

In Azure Active Directory samples (https://github.com/AzureADSamples) this object utilized to retrieve token within app controllers. Youcan implement your own caching to retrieve it in a same manner.

In your controller code you can do following:

IOwinContext owinContext = HttpContext.GetOwinContext();
                string userObjectID = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
                NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, cache);
                TokenCacheItem kdAPITokenCache = authContext.TokenCache.ReadItems().Where(c => c.Resource == "You API Resource ID").FirstOrDefault();

You can store token in claims as well if your are obtaining tokens not though AuthenticationContext (3d party apis)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!