Oauth 2.0 无法使Microsoft.Owin连接到Identity Server 4

Oauth 2.0 无法使Microsoft.Owin连接到Identity Server 4,oauth-2.0,identityserver4,openid-connect,Oauth 2.0,Identityserver4,Openid Connect,我有一个MVC5 ASP.Net web应用程序,我想通过IdentityServer4使用OAuth2 OpenId Connect。 因此,我在web项目中的启动文件是 using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Owin; using SIR.API.Caller.Helpers; namespace SIR.API.Caller { publi

我有一个MVC5 ASP.Net web应用程序,我想通过IdentityServer4使用OAuth2 OpenId Connect。 因此,我在web项目中的启动文件是

using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using SIR.API.Caller.Helpers;

namespace SIR.API.Caller
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = Settings.SignInAsAuthenticationType    // "Cookies";
            });

            app.UseOpenIdConnectAuthentication(openIdConnectOptions: new OpenIdConnectAuthenticationOptions
            {
                Authority = Settings.AuthorityUrl,      //ID Server,  "https://localhost:44314/";
                ClientId = Settings.ClientId,           // "SIR"
                Scope = Settings.Scope,                 // "openid profile";
                ResponseType = Settings.ResponseType,   // "id_token code";
                SignInAsAuthenticationType = Settings.SignInAsAuthenticationType,
                                                        // "Cookies";
                RedirectUri = Settings.RedirectUri,     //URL of website, http://localhost:53200/signin-oidc;
                RequireHttpsMetadata = Settings.RequireHttpsMetadata
                                                        // true
            });

            app.Use(async (ctx, next) =>
            {
                var message = ctx.Authentication.User.Identity.IsAuthenticated
                    ? $"User: {ctx.Authentication.User.Identity.Name}"
                    : "User Not Authenticated";
                //log.Info(message);
                await next();
            });
        }
    }
}
在Identity Server 4代码中,启动为

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mulalley.OAuth2.Configuration;
using Mulalley.OAuth2.Helpers;
using System.Linq;
using System.Security.Cryptography.X509Certificates;

namespace Mulalley.OAuth2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddIdentityServer()
                .AddSigningCredential(new X509Certificate2(Settings.CertPath, Settings.Password))
                .AddTestUsers(InMemoryConfiguration.Users().ToList())
                .AddInMemoryClients(InMemoryConfiguration.Clients())
                .AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources());

            services.Configure<IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication = false;
            });
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = Settings.AuthorityUrl;
                    options.ApiName = Settings.ApiName;
                    options.RequireHttpsMetadata = false;
                });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
}
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Logging;
使用Mulalley.OAuth2.Configuration;
使用Mulalley.OAuth2.Helpers;
使用System.Linq;
使用System.Security.Cryptography.X509证书;
名称空间Mulalley.OAuth2
{
公营创业
{
//此方法由运行时调用。请使用此方法将服务添加到容器中。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
services.AddIdentityServer()
.AddSigningCredential(新X509Certificate2(Settings.CertPath,Settings.Password))
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddInMemoryClient(InMemoryConfiguration.Clients())
.AddInMemoryIdentityResources(在MemoryConfiguration.GetIdentityResources()中);
配置(iis=>
{
iis.AuthenticationDisplayName=“Windows”;
iis.AutomaticAuthentication=false;
});
服务。添加身份验证(“承载人”)
.AddIdentityServerAuthentication(选项=>
{
options.Authority=Settings.AuthorityUrl;
options.ApiName=Settings.ApiName;
options.RequireHttpsMetadata=false;
});
services.AddAuthorization(选项=>
{
options.DefaultPolicy=新授权PolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()文件
.Build();
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware();
app.UseIdentityServer();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
哪个使用

using System.Collections.Generic;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;

namespace Mulalley.OAuth2.Configuration
{
    public class InMemoryConfiguration
    {
        public static IEnumerable<ApiResource> ApiResources()
        {
            return new[]
            {
                new ApiResource("SIR", "Service Inspection Report")
            };
        }

        public static IEnumerable<Client> Clients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "SIR",
                    ClientName = "SIR",
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    AllowedScopes = new[]
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    },
                    RedirectUris = { "https://localhost:44314" }
        }
            };
        }

        public static IEnumerable<TestUser> Users()
        {
            return new[]
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "slartibartfast",
                    Password = "password"
                }
            };
        }

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            };
        }
    }
}
使用System.Collections.Generic;
使用IdentityServer4;
使用IdentityServer4.Models;
使用IdentityServer 4.测试;
名称空间Mulalley.OAuth2.Configuration
{
内存配置中的公共类
{
公共静态IEnumerable ApiResources()
{
返回新的[]
{
新资源(“SIR”,“服务检查报告”)
};
}
公共静态IEnumerable客户端()
{
返回新的[]
{
新客户
{
ClientId=“先生”,
ClientName=“先生”,
AllowedGrantTypes=GrantTypes.Hybrid,
AllowedScopes=new[]
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
重定向URI={”https://localhost:44314" }
}
};
}
公共静态IEnumerable用户()
{
返回新的[]
{
新测试用户
{
SubjectId=“1”,
Username=“slartibartfast”,
Password=“Password”
}
};
}
公共静态IEnumerable GetIdentityResources()
{
返回新列表
{
新标识资源.OpenId(),
新的IdentityResources.Profile()
};
}
}
}
我得到这个错误:抱歉,有一个错误:未经授权的\u客户端 未知客户端或未启用客户端

或者有时候我很抱歉,出现了一个错误:未经授权的客户 无效的重定向uri


如何修复此问题?

您收到一个无效的重定向uri错误。这可以通过更正IdentityServer部件上的客户端配置来解决

具体来说,您需要将应用程序的正确重定向uri添加到
InMemoryConfiguration.Clients()
方法中的
RedirectUris
集合中

new Client
{
    ClientId = "SIR",
    ClientName = "SIR",
    AllowedGrantTypes = GrantTypes.Hybrid,
    AllowedScopes = new[]
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile
    },
    RedirectUris = { 
        "https://localhost:44314",
        "http://localhost:53200/signin-oidc"
    }

谢谢你。它似乎已经修复了一些东西,但我现在得到了这个未处理的异常,我找不到任何有用的参考来修复它;“IDX20803:无法从“[PII已隐藏]”获取配置。这是因为它无法获取证书。为什么不尝试使用AddDeveloperSigningCredentials()或类似的东西进行本地开发人员测试呢?不,我的错,代码执行被卡在断点上,我没有注意到。我现在发现我有一个新问题。IdentityServer4库中正在引发异常;url字段中的NullReferenceException在AddQueryString方法中为null