简体   繁体   English

在ASP.NET OWIN OpenIdConnect代码授权流程中通过基于令牌的身份验证替换Cookie

[英]Replacing Cookie by Token based authentication in ASP.NET OWIN OpenIdConnect code authorization flow

We have a web application written in ASP.NET that uses MVC for serving our Single Page Applications and Web API for ajax calls. 我们有一个用ASP.NET编写的Web应用程序,它使用MVC为我们的单页应用程序和用于ajax调用的Web API提供服务。

The authentication uses Microsoft.Owin and OpenIdConnect with Azure AD for Authority. 身份验证使用Microsoft.OwinOpenIdConnect与Azure AD for Authority。 The OAUTH flow is server side code authorization. OAUTH流程是服务器端代码授权。 Then in Startup.Auth.cs we have 然后在Startup.Auth.cs中我们有

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        var cookieAuthenticationOptions = new CookieAuthenticationOptions()
        {
            CookieName = CookieName,
            ExpireTimeSpan = TimeSpan.FromDays(30),
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            SlidingExpiration = true,
        };
        app.UseCookieAuthentication(cookieAuthenticationOptions);
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                   AuthorizationCodeReceived = (context) =>
                    {
                        /*exchange authorization code for a token 
                        stored on database to access API registered on AzureAD (using ADAL.NET) */
                    },

                    RedirectToIdentityProvider = (RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context) =>
                    {
                        /* Set the redirects URI here*/
                    },
            });
    }

When clicking on signin we navigate to an url whose routes map to the methods of the following MVC controller 单击登录时,我们导航到一个URL,其路由映射到以下MVC控制器的方法

public class AccountController : Controller
{
    public void SignIn(string signalrRef)
    {
        var authenticationProperties = /* Proper auth properties, redirect etc.*/
        HttpContext.GetOwinContext()
            .Authentication.Challenge(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
    }

    public void SignOut(string signalrRef)
    {
       var authenticationProperties = /* Proper auth properties, redirect etc.*/
       HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties,
            OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
    }

Then the end-user connected to our application is authenticated between our client apps and the ASP.net server using an ASP.NET cookie. 然后,连接到我们的应用程序的最终用户使用ASP.NET cookie在我们的客户端应用程序和ASP.net服务器之间进行身份验证。 We would like to use Token Based approach instead . 我们想要使用基于令牌的方法 If you are interested this is the reason . 如果您有兴趣, 这就是原因

I tried to replace the Nuget package Microsoft.Owin.Security.Cookies by Microsoft.Owin.Security.OAuth and in Startup.cs replacing 我试图用Microsoft.Owin.Security.OAuth替换Nuget包Microsoft.Owin.Security.Cookies并在Startup.cs中替换

app.UseCookieAuthentication(cookieAuthenticationOptions); by app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); by app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

and in my AccountController we changed the challenge from HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); 在我的AccountController中,我们改变了来自HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);的挑战HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); to HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, OAuthDefaults.AuthenticationType); to HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, OAuthDefaults.AuthenticationType);

The problem is that with Cookie the set-cookie was automatically sent in web request respond when the flow completes while redirecting to the url we specified. 问题是,使用Cookie时,当流程完成时, set-cookie会在Web请求中自动发送,同时重定向到我们指定的url。 Where can I find the Bearer generated by OWIN with UseOAuthBearerAuthentication (if there is any) **, **Where and When should I send it back to my client SPAs 我在哪里可以找到OWIN使用UseOAuthBearerAuthentication生成的承载(如果有的话)**,**我应该何时何地将其发送回我的客户端SPA

Note: an open source sample of what we are trying to do can be found in this github repository . 注意:可以在此github存储库中找到我们尝试执行的操作的开源示例。

I think there are two approaches for you to consider. 我认为有两种方法可供您考虑。

  1. Use javascript libraries to perform sign-in & token acquisition within your single page app. 使用javascript库在单页应用中执行登录和令牌获取。 Then your backend is purely an web API, and can just use OAuth bearer middleware to authenticate requests. 然后你的后端纯粹是一个Web API,可以使用OAuth承载中间件来验证请求。 The backend doesn't know anything about signing the user in. We have a good sample that takes this approach here . 后端对用户签名一无所知。我们有一个很好的样本,在这里采用这种方法。 If your backend needs to make API calls as well, you could consider the OnBehalfOf flow as well. 如果您的后端也需要进行API调用,您也可以考虑使用OnBehalfOf流程。 I usually recommend this approach. 我通常推荐这种方法。
  2. Use the OpenIDConnect middleware in your server to perform user sign-in and token acquisition. 使用服务器中的OpenIDConnect中间件执行用户登录和令牌获取。 You might even be able to omit the usage of the CookieAuthenticationMiddleware entirely (although I'm not 100% sure). 您甚至可以完全省略CookieAuthenticationMiddleware的使用(尽管我不是100%肯定)。 You can capture the token in the AuthorizationCodeReceived notification as you mention, and you could redirect back to your SPA with the token in the fragment of the URL. 您可以在提及的AuthorizationCodeReceived通知中捕获令牌,并且可以使用URL片段中的令牌重定向回SPA。 You could also have some route which delivers the tokens (which are cached on your server) down to your javascript. 您还可以使用一些路由将令牌(缓存在您的服务器上)下载到您的javascript。 In either case, you'll need to ensure that an outside caller can't get access to your tokens. 在任何一种情况下,您都需要确保外部呼叫者无法访问您的令牌。

The thing to keep in mind will be how you refresh tokens when they expire. 需要记住的是如何在令牌过期时刷新令牌。 If you use #1, most of it will be handled for you by libraries. 如果您使用#1,大部分将由图书馆为您处理。 If you use #2, you'll have to manage it more yourself. 如果你使用#2,你将不得不自己管理它。

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

相关问题 ASP.NET OWIN自定义Cookie身份验证 - ASP.NET OWIN Custom Cookie Authentication 将ASP.NET Core WEB API令牌身份验证与OWIN / Katana OAuth 2.0授权服务器一起用作资源服务器 - Use ASP.NET Core WEB API token authentication as a resourceserver with OWIN/Katana OAuth 2.0 Authorization Server 没有OWIN和AspNet.Identity的基于Asp.Net Web Api令牌的授权 - Asp.Net Web Api Token Based Authorization WITHOUT OWIN and AspNet.Identity 使用Owin OpenId身份验证混合Owin Asp.Net身份Cookie身份验证 - Mixing Owin Asp.Net Identity Cookie Authentication with Owin OpenId Authentication 使用jwt和openidconnect的ASP.NET框架身份验证 - ASP.NET framework authentication with jwt and openidconnect Knockout中的ASP.Net WebAPI Owin身份验证令牌 - ASP.Net WebAPI Owin authentication token in Knockout 如何在基于 cookie 身份验证的 asp.net mvc 项目中向 web api 添加令牌身份验证 - How to Add token authentication to web api in cookie authentication based asp.net mvc project Asp.Net MVC 6 Cookie身份验证 - 授权失败 - Asp.Net MVC 6 Cookie Authentication - Authorization fails ASP.NET Web App 的授权码流代码示例 - Authorization Code Flow code examples for ASP.NET Web App 在 ASP.NET Core 中结合 cookie 和令牌身份验证 - Combining cookie and token authentication in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM