【问题标题】:Adding Bearer token to cookie after web api authenticationWeb api身份验证后将Bearer令牌添加到cookie
【发布时间】:2020-01-14 12:06:53
【问题描述】:

在我的 MVC Core 应用程序中,我让用户通过以下配置登录 Azure

public void Configure(string name, OpenIdConnectOptions options) {
                options.ClientId = _azureOptions.ClientId;
                options.Authority = _azureOptions.Authority;
                options.UseTokenLifetime = true;
                options.CallbackPath = _azureOptions.CallbackPath;
                options.RequireHttpsMetadata = false;
                options.ClientSecret = _azureOptions.ClientSecret;
                options.Resource = "https://graph.microsoft.com"; // AAD graph
                options.SaveTokens = true;
                // Without overriding the response type (which by default is id_token), the OnAuthorizationCodeReceived event is not called.
                // but instead OnTokenValidated event is called. Here we request both so that OnTokenValidated is called first which 
                // ensures that context.Principal has a non-null value when OnAuthorizeationCodeReceived is called
                options.ResponseType = "id_token code";

                // Subscribing to the OIDC events
                options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
                //options.Events.OnAuthenticationFailed = OnAuthenticationFailed;
            }

然后,一旦我通过 AcquireTokenByAuthorizationCodeAsync 方法从 Azure 获得了不记名令牌,然后我将该不记名令牌发送到我的 Web API,该 API 返回另一个不记名令牌,然后将在 MVC 应用程序中用作未来调用的身份验证进入 Web API。

我的问题是,我如何将第二个不记名令牌保存为 cookie,以便我可以在每次向 API 请求时发送它,或者有更好的方法吗?

【问题讨论】:

    标签: azure asp.net-core-mvc asp.net-core-webapi


    【解决方案1】:

    bearer tokens 的客户端存储有两种模式:cookiesusing HTML5 local storage

    如果 cookie 用于将不记名令牌从客户端传输到服务器,那么 cookie 也将用于在客户端存储不记名令牌。

    同样,如果授权标头用于传输令牌,则必须使用 HTML5 本地存储(或会话存储)来存储不记名令牌。

    您可以将此 SO 线程引用到代码部分 store Bearer Token in MVC

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login"),
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2014-07-06
      • 2014-11-18
      • 2020-01-23
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多