OWIN OpenID 连接授权无法授权安全控制器/操作

OWIN OpenID connect authorization fails to authorize secured controller / actions(OWIN OpenID 连接授权无法授权安全控制器/操作)

本文介绍了OWIN OpenID 连接授权无法授权安全控制器/操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个项目,其中第三方提供商将充当基于 Oauth2 的授权服务器.一个基于 Asp.net MVC 5 的客户端,它将用户发送到授权服务器进行身份验证(使用登录名/密码),并且身份验证服务器将返回一个访问令牌返回给 MVC 客户端.对资源服务器 (API) 的任何进一步调用都将使用访问令牌进行.

I am working on a project where a third party provider will act as an Oauth2 based Authorization Server. An Asp.net MVC 5 based client which will send the user to the authorization server to authenticate (using login / password) and the auth server will return an access token back to the MVC client. Any further calls to resource servers (APIs) will be made using the access token.

为了实现这一点,我使用了 Microsoft.Owin.Security.OpenIdConnect 和 UseOpenIdConnectAuthentication 扩展.我能够成功重定向并从身份验证服务器获取访问令牌,但客户端没有创建身份验证 Cookie.每次我尝试访问安全页面时,都会获得带有访问令牌的回调页面.

To achieve this I am using Microsoft.Owin.Security.OpenIdConnect and the UseOpenIdConnectAuthentication extension. I am able to successfully redirect and get the access token from the auth server but the client is not creating an Authentication Cookie. Every time I try to access a secured page, I get the callback page with access token.

我在这里缺少什么?我当前的代码如下.

What am I missing here? My current code is below.

安全控制器操作:

namespace MvcWebApp.Controllers
{    
    public class SecuredController : Controller
    {
        // GET: Secured
        [Authorize]
        public ActionResult Index()
        {
            return View((User as ClaimsPrincipal).Claims);
        }
    }
}

启动类:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType("ClientCookie");

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AuthenticationType = "ClientCookie",
            CookieName = CookieAuthenticationDefaults.CookiePrefix + "ClientCookie",
            ExpireTimeSpan = TimeSpan.FromMinutes(5)
        });

        // ***************************************************************************
        // Approach 1 : ResponseType = "id_token token"
        // ***************************************************************************
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
            SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(),
            Authority = "https://thirdparty.com.au/oauth2",
            ClientId = "_Th4GVMa0JSrJ8RKcZrzbcexk5ca",
            ClientSecret = "a3GVJJbLHkrn9nJRj3IGNvk5eGQa",
            RedirectUri = "http://mvcwebapp.local/",
            ResponseType = "id_token token",
            Scope = "openid",

            Configuration = new OpenIdConnectConfiguration
            {
                AuthorizationEndpoint = "https://thirdparty.com.au/oauth2/authorize",
                TokenEndpoint = "https://thirdparty.com.au/oauth2/token",
                UserInfoEndpoint = "https://thirdparty.com.au/oauth2/userinfo",
            },

            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = n =>
                {
                    var token = n.ProtocolMessage.AccessToken;

                    // persist access token in cookie
                    if (!string.IsNullOrEmpty(token))
                    {
                        n.AuthenticationTicket.Identity.AddClaim(
                            new Claim("access_token", token));
                    }

                    return Task.FromResult(0);
                },

                AuthenticationFailed = notification =>
                {
                    if (string.Equals(notification.ProtocolMessage.Error, "access_denied", StringComparison.Ordinal))
                    {
                        notification.HandleResponse();

                        notification.Response.Redirect("/");
                    }

                    return Task.FromResult<object>(null);
                }
            }
        });

        // ***************************************************************************
        // Approach 2 : ResponseType = "code"
        // ***************************************************************************
        //app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        //{
        //    AuthenticationMode = AuthenticationMode.Active,
        //    AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
        //    SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(),
        //    Authority = "https://thirdparty.com.au/oauth2",
        //    ClientId = "_Th4GVMa0JSrJ8RKcZrzbcexk5ca",
        //    ClientSecret = "a3GVJJbLHkrn9nJRj3IGNvk5eGQa",
        //    RedirectUri = "http://mvcwebapp.local/",
        //    ResponseType = "code",
        //    Scope = "openid",

        //    Configuration = new OpenIdConnectConfiguration
        //    {
        //        AuthorizationEndpoint = "https://thirdparty.com.au/oauth2/authorize",
        //        TokenEndpoint = "https://thirdparty.com.au/oauth2/token",
        //        UserInfoEndpoint = "https://thirdparty.com.au/oauth2/userinfo",
        //    },

        //    Notifications = new OpenIdConnectAuthenticationNotifications
        //    {
        //        AuthorizationCodeReceived = async (notification) =>
        //        {
        //            using (var client = new HttpClient())
        //            {
        //                var configuration = await notification.Options.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);                                        
        //                var request = new HttpRequestMessage(HttpMethod.Get, configuration.TokenEndpoint);
        //                request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        //                {
        //                    {OpenIdConnectParameterNames.ClientId, notification.Options.ClientId},
        //                    {OpenIdConnectParameterNames.ClientSecret, notification.Options.ClientSecret},
        //                    {OpenIdConnectParameterNames.Code, notification.ProtocolMessage.Code},
        //                    {OpenIdConnectParameterNames.GrantType, "authorization_code"},
        //                    {OpenIdConnectParameterNames.ResponseType, "token"},
        //                    {OpenIdConnectParameterNames.RedirectUri, notification.Options.RedirectUri}
        //                });

        //                var response = await client.SendAsync(request, notification.Request.CallCancelled);
        //                response.EnsureSuccessStatusCode();

        //                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

        //                // Add the access token to the returned ClaimsIdentity to make it easier to retrieve.
        //                notification.AuthenticationTicket.Identity.AddClaim(new Claim(
        //                    type: OpenIdConnectParameterNames.AccessToken,
        //                    value: payload.Value<string>(OpenIdConnectParameterNames.AccessToken)));
        //            }
        //        }
        //    }

        /

本文标题为:OWIN OpenID 连接授权无法授权安全控制器/操作

基础教程推荐