Web API .net 框架
我使用 IdentityServer4 .net core 1.1 完成了身份验证服务。 客户端设置如下:
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
// resource owner password grant client
new Client
{
ClientId = "ro.client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
// OpenID Connect hybrid flow and client credentials client (MVC)
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
RequireConsent = true,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
},
// JavaScript Client
new Client
{
ClientId = "js",
ClientName = "JavaScript Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = { "http://localhost/web/main.html#/redirectLogin#" },
PostLogoutRedirectUris = { "http://localhost/web" },
AllowedCorsOrigins = { "http://localhost" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
RequireConsent = false
}
我有一个使用 oidc-client 的 javascript 前端应用程序。 在其中我可以使用以下设置向身份验证服务器进行身份验证:
var userManagerConfig = {
authority: "http://localhost:5000",
client_id: "js",
redirect_uri: "http://localhost/web/main.html#/redirectLogin#",
response_type: "id_token token",
scope: "openid profile api1",
post_logout_redirect_uri: "http://localhost/web",
};
var userManager = new Oidc.UserManager(userManagerConfig);
我还有一个在 .net framework 4.6.1 中制作的 api web。 在其中我想从前端接收身份验证并使用身份验证服务器来验证访问。
这种情况应该如何设置?
最佳答案
您的 API 应在 Identity Server 中注册为 API 资源。然后 - 它应该实现 OwinStartup 并在其中包含:
public void Configuration(IAppBuilder app)
{
// accept access tokens from identityserver and require a scope of 'api1'
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "<ids address>",
ValidationMode = ValidationMode.Both,
RequiredScopes = new[] { "myapi" }
});
// configure web api
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
而且,因为是.NET Framework API,所以需要引用IdentityServer3.AccessTokenValidation
。这不应该打扰您并引起任何担忧。它毫不犹豫地处理 IdentityServer4 token 。
其他一切都是标准的——你需要在你想要的所有 Controller /方法上使用 AuthorizeAttribute
或添加这个:
// require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute());
在 Startup.cs
中并在所有 Controller 上强制授权。
关于c# - Web Api .net 框架 4.6.1 和 identityServer4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041098/