我希望我的 Identity Server 4 服务器提供附加服务(例如,"MyAdditionalService"
)对于一些注册客户。他们将通过在服务器上定义的自定义端点来使用该服务。
我正在考虑为我的该服务定义一个 API(例如,名为“myAdditionalService”),以便可以根据客户端的配置向客户端授予对此类服务的访问权限。但是,我不确定如何限制对端点(MVC - 操作方法)的访问,仅允许允许使用 API 的客户端(可能代表用户)。
我发现我可以这样做:
services.AddAuthorization(options =>
{
options.AddPolicy("MyAdditionalServicePolicy",
policy => policy.RequireClaim("scope",
"myAdditionalService"));
});
并使用属性[Authorize("MyAdditionalServicePolicy")]
装饰用于访问此类服务的操作方法。但是,我不知道服务器是否可以同时作为API,甚至不知道是否可能。
我怎样才能实现这个?令人困惑的是,令牌服务也扮演着 API 的角色,因为它保护对操作方法或端点的访问。
Thanks.
UPDATE:
我的网络应用程序是一个 IdentityServerWithAspNetIdentity ,它已经使用了 Asp.net core Identity 的身份验证机制。举个例子,如果向某些注册客户提供的附加服务,我的 Web 应用程序是用户的 Twitter 好友列表(在名为 Twitter 的控制器上建模,名为 ImportFriends 的操作),因此 api 称为“TwitterFriends”
根据下面回复的建议,我修改了我的Configure()
方法有app.UseJwtBearerAuthentication()
。我已经有了app.UseIdentity()
and app.UseIdentityServer()
如下所示:
app.UseIdentity();
app.UseIdentityServer();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AuthenticationScheme = "Bearer",
Authority = Configuration["BaseUrl"],
Audience = "TwitterFriends",
RequireHttpsMetadata = false //TODO: make true, it is false for development only
});
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseGoogleAuthentication(new GoogleOptions
{
AuthenticationScheme = "Google",
SignInScheme = "Identity.External", // this is the name of the cookie middleware registered by UseIdentity()
在专用控制器上:
[Authorize(ActiveAuthenticationSchemes = "Identity.Application,Bearer")]
//[Authorize(ActiveAuthenticationSchemes = "Identity.Application")]
//[Authorize(ActiveAuthenticationSchemes = "Bearer")]
[SecurityHeaders]
public class TwitterController : Controller
{...
但我在日志中得到了这个:
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware
[7]
Identity.Application was not authenticated. Failure message: Unprotect tic
ket failed
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.A
uthorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes (Identity.Applicatio
n, Bearer).
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware
[12]
AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[12]
AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action IdentityServerWithAspNetIdentity.Controllers.TwitterContro
ller.ImportFriends (IdentityServerWithAspNetIdentity) in 86.255ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 105.2844ms 401
我尝试了该属性的不同组合,但似乎 Identity.Application 和 Bearer 在这种情况下无法相处:收到 401。
任何帮助表示赞赏。
谢谢..