简体   繁体   English

在.NET Core Web应用程序中存储Identity Server的访问令牌

[英]Storing access token from Identity Server in NET Core web application

I have net core web application targeting an API and authenticating with Identity Server(also as web application). 我有针对API的网络核心Web应用程序,并使用Identity Server(也作为Web应用程序)进行身份验证。 Because application is web server based, I have problem with storing access token from Identity Server which application needs in every request(in Header) in order to communicate with API. 因为应用程序是基于Web服务器的,所以我存在从Identity Server存储访问令牌的问题,该应用程序需要在每个请求(在Header中)以便与API通信。 An ideal flow is: user launchs application and being prompt to enter his phone number(in order to get OTP code and authenticate), when submits phone number Identity Server with some external providers sends OTP code to user and now user is being prompt to enter OTP code. 一个理想的流程是:用户启动应用程序并提示输入他的电话号码(以获取OTP代码并进行身份验证),当提交电话号码时,Identity Server与某些外部提供商向用户发送OTP代码,现在用户正在提示输入OTP代码。 After successuflly submits OTP code, Identity Server verifies it and give access token to client. 成功提交OTP代码后,Identity Server会对其进行验证并向客户端提供访问令牌。 And this is point where problem starts. 这就是问题开始的关键所在。

First I tried to store access token with singleton that after otp validation stores(in some dictionary) access token related with phone number as key. 首先,我尝试使用单件存储访问令牌,在otp验证后存储(在某些字典中)访问与电话号码相关的令牌作为密钥。 But, problem is because application is webserver based and in production on server it is not mandatory that each user will have his application instance running on server, so singleton is useless beacese most likely we have at example 3-4 application running for 20 users and in that situation more than one users uses same singleton! 但是,问题是因为应用程序是基于Web服务器的,并且在服务器上的生产中并不是每个用户都必须在服务器上运行他的应用程序实例,所以单例是无用的,因为我们在示例3-4应用程序运行20个用户并且在那种情况下,不止一个用户使用相同的单身人士! Then I googled and found that best option is to store access token or some realted keys for that token in browser session or document cookie. 然后我用谷歌搜索,发现最好的选择是在浏览器会话或文档cookie中存储访问令牌或该令牌的一些实际密钥。 So now application is working in way that after OTP code validation user's phone number and access token stores in Dictionary collection(now more users use same collection, beacuse singleton is useless for this) where key is phone number and access token is value, then javascript triggers and set user phone number in cookie(in each request) and now when creating Bearer header I simply read cookie from current reqeust and with that phone number i take access token from collection. 所以现在应用程序的工作方式是,在OTP代码验证后,用户的电话号码和访问令牌存储在Dictionary集合中(现在更多的用户使用相同的集合,因为单身对此没用),其中密钥是电话号码,访问令牌是值,然后javascript触发并在cookie中设置用户电话号码(在每个请求中),现在在创建Bearer标题时,我只需从当前请求中读取cookie,并使用该电话号码从集合中获取访问令牌。 So this solution is very bad because everything(after logging in) that you need to get access token is to modify phone number in cookie and if you are lucky and match some existing number in collection you will get access token and easily get access to API. 所以这个解决方案非常糟糕,因为您需要获取访问令牌的所有内容(登录后)都是修改cookie中的电话号码,如果您很幸运并且匹配集合中的某些现有号码,您将获得访问令牌并轻松访问API 。

Down below is method that is being called in each request in order to get access token from collection where access token with phone number was put after otp validation. 下面是在每个请求中调用的方法,以便从集合中获取访问令牌,其中在otp验证之后放置具有电话号码的访问令牌。

public async Task<string> GetAccessToken()
        {
            string phoneNumber = GetUserPhoneNumber();

            if (string.IsNullOrEmpty(phoneNumber))
                throw new ArgumentNullException(nameof(phoneNumber));

            if (_usersTokenStore == null || _usersTokenStore.Count == 0)
                throw new NotImplementedException(nameof(_usersTokenStore));

            var refSingleUser = new SingleUserTokenStore();
            bool userHaveAccessToken = _usersTokenStore.TryGetValue(phoneNumber, out refSingleUser);

            if (!userHaveAccessToken)
                throw new Exception($"User with {phoneNumber} not authorized.");

            if (refSingleUser.IsTimeToRefreshToken)
               return await RefreshAndGetAccessToken();

            return refSingleUser.AccessToken;
        }


private string GetUserPhoneNumber()
        {
            if (_httpContext == null)
                throw new ArgumentException(nameof(_httpContext));

            var phoneNumberCookie = _httpContext.HttpContext.Request.Cookies.Where(c => c.Key == "phone_number").FirstOrDefault();

            if (phoneNumberCookie.Value == null || phoneNumberCookie.Key == null)
                return null;

            return phoneNumberCookie.Value;
        }

It's unclear what you're doing here. 目前还不清楚你在这里做什么。 If this is a web application (ie the user is presented with HTML views that they navigate between in a web browser), then you need to employ cookie authentication. 如果这是一个Web应用程序(即向用户显示他们在Web浏览器中导航的HTML视图),那么您需要使用cookie身份验证。 There is no way for the user of a web browser to pass an Authorization header with each request. Web浏览器的用户无法为每个请求传递Authorization标头。 Cookie auth is the only way to persist authentication in a web browser. Cookie auth是在Web浏览器中持久身份验证的唯一方法。

If this is an API, then it is on the client to store the access token and submit it along with each request via the Authorization header. 如果这是一个API,则客户端将存储访问令牌,并通过Authorization标头将其与每个请求一起提交。

In either case, you should not persist the auth token server-side. 在任何一种情况下,您都不应该持久化auth令牌服务器端。 That is not the responsibility of the server. 这不是服务器的责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Xamarin 应用程序中的身份服务器获取 OAuth 访问令牌 - Obtaining OAuth access token from identity server within Xamarin application 使用 Microsoft 标识为 ASP.NET 核心 web 应用程序检索不记名令牌 - Retrieving a Bearer token using Microsoft Identity for an ASP.NET core web application 如何在ASP Net 4.7 MVC应用程序中获取Identity Server 4的access_token - How to get Identity Server 4's access_token in ASP Net 4.7 MVC Application 从ASP.NET Core Web API中的控制器访问用户标识 - Access user identity from controller in ASP.NET Core Web API 使用Identity Server在.Net Core Web API中授权 - Authorization in .Net Core Web API using Identity Server ASP.NET 核心授权权限访问文件夹与Identity Server - ASP.NET Core authorization permission access folder with Identity Server Asp.net 核心 3 身份服务器 4 应用程序崩溃 堆栈内存溢出 - Asp.net core 3 Identity server 4 application crash Stack Overflow 从asp.net核心身份验证Web应用程序获取Microsoft Graph的访问令牌 - Getting Access Token for Microsoft Graph from asp.net core Authentication web app 在 .NET core 2 MVC 应用程序中配置 JWT 访问令牌 - Configure JWT Access Token in .NET core 2 MVC application 来自 ASP.NET Core 身份的 Application Insights 用户 ID - Application Insights User ID from ASP.NET Core identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM