在不是核心的.Net WepAPI 2上设置身份验证令牌验证,使用Identity Server 4。
在不是核心的.Net WepAPI 2上设置身份验证令牌验证,使用Identity Server 4。
我知道如何在.Net Core中设置IdentityServer 4身份验证。就是使用在IdentityServer4.AccessTokenValidation中定义的扩展。我会在我的启动类中这样设置:\n
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions { Authority = "http://localhost:5000", RequireHttpsMetadata = false, ApiName = "webapi" });
\n问题是现在我需要对一个不是Core的.NET 4.6 Web API进行身份验证请求。但是相同的包对此不起作用。\n根据这个问题,我只需要使用同一个用于Identity server 3的包:IdentityServer3.AccessTokenValidation。\n但是尝试后,当我向Web API发出请求时,我得到的结果是401,而我不知道如何连接身份验证事件以了解其原因。这是我的配置:\nApi Startup.cs:\n
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority = "http://localhost:5000", RequiredScopes = new[] { "webapi" }, });
\nClient Startup.cs:\n
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { AuthenticationType = "oidc", SignInAsAuthenticationType = "Cookies", Authority = "http://localhost:5000", RedirectUri = "http://localhost:3954/signin-oidc", ClientId = "MvcClient", Scope = "openid profile webapi offline_access", ResponseType = "code id_token", ClientSecret = "secret", UseTokenLifetime = false, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, }, });
\nClient项目中的TestController:\n
var tokenClient = new TokenClient("http://localhost:5000/connect/token", "MvcClient", "secret"); var tokenResponse = await tokenClient.RequestClientCredentialsAsync("webapi"); var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); var content = await client.GetStringAsync("http://localhost:5004/api/identity");
\n我在这里成功获得了访问令牌。但是当向api/identity
发出请求时,得到的结果是401。\n这是IDP中的配置:\n
new ApiResource("webapi", "My API") [...] new Client { ClientId = "MvcClient", ClientName = "MVC Client", AllowedGrantTypes = GrantTypes.HybridAndClientCredentials, RequireConsent = true, ClientSecrets = { new Secret("secret".Sha256()) }, RedirectUris = { "http://localhost:3954/signin-oidc" }, PostLogoutRedirectUris = { "http://localhost:3954/signout-callback-oidc" }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "netcoremvcapi", "webapi" }, AllowOfflineAccess = true, }
\n有什么想法为什么会失败吗?我是否错误地认为我可以使用IdentityServer3.AccessTokenValidation来验证令牌?
问题的原因是启动类没有被调用,解决方法是添加Microsoft.Owin.Host.SystemWeb包。然后,注册OpenIdConnectAuthenticationMiddleware到OWIN运行时时发生异常,原因是我的Web API 2项目正在使用Owin实现的Katana,并且Katana不支持该包的v5.0版本。所以,我必须首先删除该包(降级由于依赖关系无法进行),但由于依赖于Microsoft.Owin.Security.Jwt包的版本,删除失败。这当然又导致了另一个包的依赖问题...在删除所有相关包并重新安装System.IdentityModel.Tokens.Jwt v4.0.2和IdentityServer3.AccessTokenValidation后,与上述相同的设置一切正常。