如何使用OWIN中间件在Web Api中实现OAuth2 Authorization_Code流程?

Jos*_*den 10 c# oauth-2.0 asp.net-web-api owin

我正在尝试创建一个简单的概念验证OAuth启用的应用程序,但我坚持授权代码实现.我读到的每个地方看起来都是这样或那样,从来没有实际使用过授权代码流.我一直在使用以下资源获取信息:

我已经使用自定义OAuthAuthorizationServerProvider设置了web api和owin,以接受刷新令牌的密码授予类型以及为访问令牌交换刷新令牌的功能.这很好用,但我想设置一个场景,我将浏览器重定向到服务器以授权并使用授权代码重定向回客户端.然后,我希望客户端将授权代码发送到令牌端点以获取刷新令牌

在Web Server Apps下的第二个链接中,我正在尝试让我的web api应用程序显示来自请求的授权代码,例如http://127.0.0.1/auth?response_type=code&client_id=123&redirect_uri=http://validredirect .com&scope = access,但我一直得到404.

我已将owin配置如下:

var databaseContext = new AdnsfContext();

WebApp.Start(
    new StartOptions("http://127.0.0.1:7000"),
    appBuilder =>
    {
        var httpConfig = new HttpConfiguration();
        httpConfig.MapHttpAttributeRoutes();
        httpConfig.SuppressDefaultHostAuthentication();
        httpConfig.Filters.Add(new HostAuthenticationFilter("Bearer"));

        appBuilder
            .UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AllowInsecureHttp = true,
                    ApplicationCanDisplayErrors = true,
                    AuthorizeEndpointPath = new PathString("/auth"),
                    TokenEndpointPath = new PathString("/token"),
                    AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
                    Provider = new AuthServerProvider(),
                    AuthorizationCodeProvider = new AuthorizationCodeProvider(),
                    RefreshTokenProvider = new RefreshTokenProvider(),
                })
            .UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AuthenticationType = "Bearer",
                })
            .UseCors(CorsOptions.AllowAll)
            .UseWebApi(httpConfig);
    });
Run Code Online (Sandbox Code Playgroud)

我为启用授权端点而添加的部分是auth服务器选项的属性:

AuthorizeEndpointPath = new PathString("/auth"),
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
AuthorizationCodeProvider = new AuthorizationCodeProvider(),
Run Code Online (Sandbox Code Playgroud)

我的AuthorizationCodeProvider实现中的覆盖抛出未实现的异常,但它目前甚至没有命中代码中设置的任何断点.需要注意的一点是,当我使用postman命中auth端点时,我得到一个HTTPAPI/2.0的服务器头,这与在该端点上没有表面的东西不同,这意味着我必须发送请求不正确.任何人都可以看到我的设置有问题吗?在此先感谢,我知道这显然是我对OWIN和OAuth的理解失败.

bal*_*ias 3

看一下IdentityServer。它基于欧文。还有示例存储库,您可以在其中找到许多使用自行部署和/或第三方身份提供商的示例。

我认为这个例子最适合你。

  • @JoshuaBelden 你能发布你的最终解决方案作为答案吗?或者至少是其中有意义的部分? (6认同)