mvc自定义oauth服务器不会在未经授权的情况下重定向到登录页面

问题描述 投票:1回答:1

我设置了自己的oauth授权服务器(通过Facebook,Google和公司登录)。不幸的是,在单击“授权端点”后,我的服务器没有重定向到登录页面。中间件为什么不重定向到我的登录页面?

我遵循了一些教程:

  1. OWIN OAuth 2.0 Authorization Server
  2. OAuth custom provider c#(顺便说一下,这是我找到的用于登录到自定义oauth服务器的客户端的唯一代码示例。感谢@MatthiasRamp。我阅读的所有其他内容都是关于如何使用社交媒体客户端登录的,这非常令人沮丧)
  3. MVC 5 application - implement OAuth Authorization code flow

这是我在oauth服务器端进行的缩短:

  1. [Startup.Auth.cs使用具有登录路径的活动Cookie身份验证
  2. [Startup.Auth.cs使用被动Cookie身份验证
  3. [Startup.Auth.cs通过AuthorizeEndpointPath使用授权服务器
  4. SecurityController/Authorize调用Authentication.challenge()将状态更改为401

他描述的来自@Satish P的post中的一点:

  • 将客户端重定向到登录页面

为此,我设置属性CookieAuthenticationOptions.LoginPath告诉我

LoginPath属性通知中间件它应该将传出401未经授权的状态代码进入302重定向更改为给定的登录路径。

这是我的CookieAuthenticationOptions.LoginPath,包括Startup.Auth.cs

LoginPath

我创建了一个从public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", AuthenticationMode = AuthenticationMode.Passive, LoginPath = new PathString("/Security/Login"), LogoutPath = new PathString("/Security/Logout") }); // Enable the External Sign In Cookie. app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); // The UseOAuthAuthorizationServer extension method is to setup the authorization server. The setup options are: [...] app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AuthorizeEndpointPath = new PathString("/Security/Authorize"), TokenEndpointPath = new PathString("/Token"), ApplicationCanDisplayErrors = true, #if DEBUG AllowInsecureHttp = true, #endif // Authorization server provider which controls the lifecycle of Authorization Server Provider = new ApplicationOAuthProvider(PublicClientId) }); } 派生的类。

OAuthAuthorizationServerProvider

并且这是重定向发生的地方,因为质询将更改对未授权的响应(401)。它要返回授权视图,而不是重定向到登录页面。

OAuthAuthorizationServerProvider
c# asp.net authentication oauth owin
1个回答
0
投票

我知道为时已晚,您可能不再需要它,以防万一其他人也遇到此问题,那么您需要返回HttpUnauthorizedResult();挑战后,它将重新引导您登录页面。例如

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        // [Check username and pw here]
        var oAuthIdentity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
        var cookiesIdentity = new ClaimsIdentity(new GenericIdentity(context.UserName, CookieAuthenticationDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

        AuthenticationProperties properties = CreateProperties(context.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }

        return Task.FromResult<object>(null);
    }
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        var grantType = context.Parameters.SingleOrDefault(p => p.Key == "grant_type").Value;
        if (grantType != null)
        {
            if (grantType[0] == "authorization_code")
            {
                string clientId;
                string clientSecret;
                if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret))
                {
                    if (clientId == Clients.ClientApp.Id && clientSecret == Clients.ClientApp.Secret)
                    {
                        context.Validated();
                    }
                }
            }
        }
        return Task.FromResult<object>(null);
    }  
    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {        
        if (context.ClientId == Clients.ClientApp.Id)
        {
            context.Validated(Clients.ClientApp.RedirectUrl);
        }

        return Task.FromResult<object>(null);
    }       
    public static AuthenticationProperties CreateProperties(string userName)
    {
        IDictionary<string, string> data = new Dictionary<string, string>
        {
            { "userName", userName }
        };
        return new AuthenticationProperties(data);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.