Asp.net web api Web api未重定向到identity server登录页
我正在尝试使用identity server和Web Api实现SSO 到目前为止,我已经创建了一个identity server项目和一个Web Api项目,并根据下面的说明对它们进行了配置。自从这门课程创建以来,似乎已经有了一些变化,所以我不得不做的一些事情与教程不匹配(这可能是我的痛点的原因,但我不认为是这样) 我期望发生的是,我点击了一个需要授权的控制器,如果需要,我会被重定向到Identity server登录页面。现在我拿到了401。我看了github的例子,看起来我做的事情是正确的 有人能帮我找到我丢失的东西吗 身份服务器Asp.net web api Web api未重定向到identity server登录页,asp.net-web-api,asp.net-web-api2,identityserver4,Asp.net Web Api,Asp.net Web Api2,Identityserver4,我正在尝试使用identity server和Web Api实现SSO 到目前为止,我已经创建了一个identity server项目和一个Web Api项目,并根据下面的说明对它们进行了配置。自从这门课程创建以来,似乎已经有了一些变化,所以我不得不做的一些事情与教程不匹配(这可能是我的痛点的原因,但我不认为是这样) 我期望发生的是,我点击了一个需要授权的控制器,如果需要,我会被重定向到Identity server登录页面。现在我拿到了401。我看了github的例子,看起来我做的事情是正确的
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddSigningCredential(new X509Certificate2(@"cert.pfx", "password"))
.AddInMemoryApiResources(Resources.GetApiResources())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddInMemoryClients(Clients.Get())
.AddTestUsers(Users.Get())
.AddDeveloperSigningCredential();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseDeveloperExceptionPage();//todo: add if debug
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
internal class Resources
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource> {
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource> {
new ApiResource("gateway", "Gateway Service")
};
}
}
internal class Clients
{
public static IEnumerable<Client> Get()
{
return new List<Client> {
new Client {
ClientId = "gatewayClient",
ClientSecrets = new List<Secret> { new Secret("password".Sha256())},//todo:secure password
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = new List<string> { "gateway" }
},
new Client {
ClientId = "gateway_implicitClient",
ClientSecrets = new List<Secret> { new Secret("password".Sha256())},//todo:secure password
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = new List<string> {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"gateway"
},
RedirectUris = new [] { "http://localhost:49942/signin-oidc" },
PostLogoutRedirectUris = new [] { "http://localhost:49942/signout-callback-oidc" }
}
};
}
}
internal class Users
{
public static List<TestUser> Get()
{
return new List<TestUser> {
new TestUser {
SubjectId = "5BE86359-073C-434B-AD2D-A3932222DABE",
Username = "scott",
Password = "password"
}
};
}
}
公共类启动
{
public void配置服务(IServiceCollection服务)
{
services.AddIdentityServer()
.AddSigningCredential(新的X509Certificate2(@“cert.pfx”,“密码”))
.AddInMemoryApiResources(Resources.GetApiResources())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddInMemoryClients(Clients.Get())
.AddTestUsers(Users.Get())
.AddDeveloperSigningCredential();
services.AddMvc();
}
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole();
app.UseDeveloperExceptionPage();//todo:如果调试,则添加
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
内部班级资源
{
公共静态IEnumerable GetIdentityResources()
{
返回新列表{
新标识资源.OpenId(),
新的IdentityResources.Profile()
};
}
公共静态IEnumerable
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Users\me.nuget\packages\microsoft.aspnetcore.http.extensions\2.1.1\lib\netstandard2.0\microsoft.aspnetcore.http.extensions.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.6\System.ComponentModel.Annotations.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:对筛选器“Microsoft.AspNetCore.Mvc.Authorization.authorizationFilter”处的请求的授权失败。
Microsoft.AspNetCore.Mvc.ChallengeResult:信息:使用身份验证方案()执行ChallengeResult。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.identitymodel.tokens\5.2.0\lib\netstandard1.4\microsoft.identitymodel.tokens.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\sdk\NuGetFallbackFolder\system.identitymodel.tokens.jwt\5.2.0\lib\netstandard1.4\system.identitymodel.tokens.jwt.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.6\System.Xml.ReaderWriter.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.identitymodel.logging\5.2.0\lib\netstandard1.4\microsoft.identitymodel.logging.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.identitymodel.protocols\5.2.0\lib\netstandard1.4\microsoft.identitymodel.protocols.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
“dotnet.exe”(CoreCLR:clrhost):加载了“C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.identitymodel.protocols.openidconnect\5.2.0\lib\netstandard1.4\microsoft.identitymodel.protocols.openidconnect.dll”。跳过了加载符号。模块已优化,调试器选项“仅我的代码”已启用。
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:AuthenticationScheme:BealerIdentityServerAuthenticationJWT被质询。
IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler:信息:AuthenticationScheme:承载人被质询。
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:在142.4256ms中执行的操作MyNamespace.PropertiesController.GetPropertySummaries(MyService.Gateway.Service)
Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在526.0233ms 401中完成
对于API(而不是提供HTML的服务器端web应用程序),返回401是正确的行为。这将向客户端(例如javascript客户端应用程序)发出信号它需要获得一个新的令牌。也就是说,该API的客户端负责启动隐式/混合/任意登录流,以获得合适的承载令牌
如果您采用的是OpenID Connect/OAuth2方式,那么API根本不会使用cookies进行身份验证,而只会通过AddIdentityServerAuthentication()中间件使用承载令牌身份验证。对于API(而不是提供HTML的服务器端web应用程序)返回401是正确的行为。这将向客户端(例如javascript客户端应用程序)发出信号,表明它需要获取新令牌。也就是说,正是上述API的客户端负责启动隐式/hybrid/wh
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
_container = new Container();
}
public IConfigurationRoot Configuration { get; }
private Container _container;
public void ConfigureServices(IServiceCollection services)
{
AddAuthentication(services);
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
app.UseAuthentication();
app.UseMvc();
}
private void AddAuthentication(IServiceCollection services)
{
new IdentityServerConfig(services, Configuration);
}
}
public class IdentityServerConfig
{
public IdentityServerConfig(IServiceCollection services, IConfigurationRoot configuration)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5000";
options.ApiName = "gateway_implicit";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "gateway_implicitClient";
options.SaveTokens = true;
});
}
}
[Produces("application/json")]
[Route("api/properties")]
public class PropertiesController : AuthController
{
[HttpGet]
[Route("GetProperty/{agentId}/{propertyId}")]
public async Task<IActionResult> GetProperty(int agentId, Guid propertyId)
{
return Ok(property);
}
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MyNameSpace.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class AuthController : ControllerBase
{
}
}