Oauth 2.0 OWIN授权服务器和Google/Facebook外部登录

Oauth 2.0 OWIN授权服务器和Google/Facebook外部登录,oauth-2.0,google-oauth,owin,Oauth 2.0,Google Oauth,Owin,我已经很久没有问题了 好的,我阅读并下载了示例代码。使用OWIN创建带有Google signin的授权服务器的非常好的例子。它还包括4个用于授权代码授权、客户端凭据授权、隐式授权和资源所有者密码凭据授权的客户端 为了简洁起见,我将在这里发布配置启动文件,然后是我的问题和疑问。此外,我发现使用隐式Grant客户端时存在问题。我们走吧 Startup.cs public partial class Startup { public void ConfigureAuth(IAppBuild

我已经很久没有问题了

好的,我阅读并下载了示例代码。使用OWIN创建带有Google signin的授权服务器的非常好的例子。它还包括4个用于授权代码授权、客户端凭据授权、隐式授权和资源所有者密码凭据授权的客户端

为了简洁起见,我将在这里发布配置启动文件,然后是我的问题和疑问。此外,我发现使用隐式Grant客户端时存在问题。我们走吧

Startup.cs

public partial class Startup
{

    public void ConfigureAuth(IAppBuilder app)
    {
        // Enable Application Sign In Cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Application",
            AuthenticationMode = AuthenticationMode.Passive,
            LoginPath = new PathString(Paths.LoginPath),
            LogoutPath = new PathString(Paths.LogoutPath),
        });

        // Enable External Sign In Cookie
        app.SetDefaultSignInAsAuthenticationType("External");
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "External",
            AuthenticationMode = AuthenticationMode.Passive,
            CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",
            ExpireTimeSpan = TimeSpan.FromMinutes(2),
        });

        // Enable google authentication
        //var googleOptions = new GoogleOAuth2AuthenticationOptions
        //{
        //    Caption = "Google+",
        //    ClientId = "blablabla.apps.googleusercontent.com",
        //    ClientSecret = "Q1zNmqf-U3ZffeZgcTPh760j",
        //    CallbackPath = new PathString("/OAuth/Authorize"),
        //    Provider = new GoogleOAuth2AuthenticationProvider
        //    {
        //        OnAuthenticated = async context =>
        //            {
        //                context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Identity.FindFirst(ClaimTypes.Name).Value));
        //                context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Identity.FindFirst(ClaimTypes.Email).Value));
        //                context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.User.GetValue("picture").ToString()));
        //                context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.User.GetValue("profile").ToString()));
        //                context.Identity.AddClaim(new Claim("Token", context.AccessToken));
        //            }
        //    }
        //};
        //googleOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
        //googleOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");

        //app.UseGoogleAuthentication(googleOptions);

        app.UseGoogleAuthentication();


        // Setup Authorization Server
        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AuthorizeEndpointPath = new PathString(Paths.AuthorizePath),
            TokenEndpointPath = new PathString(Paths.TokenPath),
            ApplicationCanDisplayErrors = true,
            AllowInsecureHttp = true,

            // Authorization server provider which controls the lifecycle of Authorization Server
            Provider = new OAuthAuthorizationServerProvider
            {
                OnValidateClientRedirectUri = ValidateClientRedirectUri,
                OnValidateClientAuthentication = ValidateClientAuthentication,
                OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                OnGrantClientCredentials = GrantClientCredetails
            },

            // Authorization code provider which creates and receives authorization code
            AuthorizationCodeProvider = new AuthenticationTokenProvider
            {
                OnCreate = CreateAuthenticationCode,
                OnReceive = ReceiveAuthenticationCode,
            },

            // Refresh token provider which creates and receives referesh token
            RefreshTokenProvider = new AuthenticationTokenProvider
            {
                OnCreate = CreateRefreshToken,
                OnReceive = ReceiveRefreshToken,
            }
        });
    }

    private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == Clients.Client1.Id)
        {
            context.Validated(Clients.Client1.RedirectUrl);
        }
        else if (context.ClientId == Clients.Client2.Id)
        {
            context.Validated(Clients.Client2.RedirectUrl);
        }
        return Task.FromResult(0);
    }

    private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        string clientId;
        string clientSecret;
        if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
            context.TryGetFormCredentials(out clientId, out clientSecret))
        {
            if (clientId == Clients.Client1.Id && clientSecret == Clients.Client1.Secret)
            {
                context.Validated();
            }
            else if (clientId == Clients.Client2.Id && clientSecret == Clients.Client2.Secret)
            {
                context.Validated();
            }
        }
        return Task.FromResult(0);
    }

    private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

        context.Validated(identity);

        return Task.FromResult(0);
    }

    private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
    {
        var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

        context.Validated(identity);

        return Task.FromResult(0);
    }


    private readonly ConcurrentDictionary<string, string> _authenticationCodes =
        new ConcurrentDictionary<string, string>(StringComparer.Ordinal);

    private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
    {
        context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
        _authenticationCodes[context.Token] = context.SerializeTicket();
    }

    private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
    {
        string value;
        if (_authenticationCodes.TryRemove(context.Token, out value))
        {
            context.DeserializeTicket(value);
        }
    }

    private void CreateRefreshToken(AuthenticationTokenCreateContext context)
    {
        context.SetToken(context.SerializeTicket());
    }

    private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);
    }
}
公共部分类启动
{
public void ConfigureAuth(IAppBuilder应用程序)
{
//启用应用程序登录Cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=“应用程序”,
AuthenticationMode=AuthenticationMode.Passive,
LoginPath=新路径字符串(path.LoginPath),
LogoutPath=新路径字符串(path.LogoutPath),
});
//启用外部登录Cookie
app.setDefaultSignatureAuthenticationType(“外部”);
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=“外部”,
AuthenticationMode=AuthenticationMode.Passive,
CookieName=CookieAuthenticationDefaults.CookiePrefix+“外部”,
ExpireTimeSpan=从分钟(2)开始的时间跨度,
});
//启用google身份验证
//var googleOptions=新的GoogleOAuth2AuthenticationOptions
//{
//Caption=“谷歌+”,
//ClientId=“bla.apps.googleusercontent.com”,
//ClientSecret=“Q1zNmqf-U3ZffeZgcTPh760j”,
//回调路径=新路径字符串(“/OAuth/Authorize”),
//Provider=新的GoogleOAuth2AuthenticationProvider
//    {
//OnAuthenticated=异步上下文=>
//            {
//context.Identity.AddClaim(新声明(ClaimTypes.Name,context.Identity.FindFirst(ClaimTypes.Name.Value));
//context.Identity.AddClaim(新声明(ClaimTypes.Name,context.Identity.FindFirst(ClaimTypes.Email.Value));
//context.Identity.AddClaim(新声明(ClaimTypes.Name,context.User.GetValue(“picture”).ToString());
//context.Identity.AddClaim(新声明(ClaimTypes.Name,context.User.GetValue(“profile”).ToString());
//context.Identity.AddClaim(新声明(“Token”,context.AccessToken));
//            }
//    }
//};
//googleOptions.Scope.Add(“https://www.googleapis.com/auth/plus.login");
//googleOptions.Scope.Add(“https://www.googleapis.com/auth/plus.login");
//app.UseGoogleAuthentication(谷歌选项);
app.UseGoogleAuthentication();
//设置授权服务器
app.useAuthorizationServer(新的OAuthorizationServerOptions
{
AuthorizeEndpointPath=新路径字符串(path.AuthorizePath),
TokenEndpointPath=新路径字符串(path.TokenPath),
ApplicationAndDisplayErrors=true,
AllowInsecureHttp=true,
//授权服务器提供程序,用于控制授权服务器的生命周期
Provider=新的OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri=ValidateClientRedirectUri,
OnValidateClientAuthentication=ValidateClientAuthentication,
OnGrantResourceOwnerCredentials=GrantResourceOwnerCredentials,
OnGrantClientCredentials=GrantClientCredentials详细信息
},
//创建和接收授权代码的授权代码提供程序
AuthorizationCodeProvider=新的AuthenticationTokenProvider
{
OnCreate=CreateAuthenticationCode,
OnReceive=ReceiveAuthenticationCode,
},
//刷新创建和接收referesh令牌的令牌提供程序
RefreshTokenProvider=新的AuthenticationTokenProvider
{
OnCreate=CreateRefreshToken,
OnReceive=ReceiverFreshToken,
}
});
}
专用任务ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext上下文)
{
if(context.ClientId==Clients.Client1.Id)
{
context.Validated(Clients.Client1.RedirectUrl);
}
else if(context.ClientId==Clients.Client2.Id)
{
context.Validated(Clients.Client2.RedirectUrl);
}
返回Task.FromResult(0);
}
专用任务ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)
{
字符串clientId;
字符串clientSecret;
if(context.TryGetBasicCredentials(out clientId,out clientSecret)||
TryGetFormCredentials(out clientId,out clientSecret))
{
if(clientId==Clients.Client1.Id&&clientSecret==Clients.Client1.Secret)
{
context.Validated();
}
else if(clientId==Clients.Client2.Id&&clientSecret==Clients.Client2.Secret)
{
context.Validated();
}
}
返回Task.FromResult(0);
}
专用任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
var identity=newclaimsidentity(newgenericientity(context.UserName,OAuthDefaults.AuthenticationType),context.Scope.Select(x=>newclaim(“urn:oauth:Scope”,x));
上下文验证(身份);
返回Task.FromResult(0);
}
专用任务GrantClientCredetails(OAuthGrantClientCredentialsContext)
{
var identity=new-ClaimsIdentity(新的GenericEntity(context.ClientId,OAuthDefaults.AuthenticationType),context。