我有一个ASP.net MVC5客户端(WEBAPP),它使用身份验证 服务器。我正在使用以下代码访问web api。
1.从Identity Server获取访问令牌
private async Task<TokenResponse> GetTokenAsync()
{
var client = new TokenClient(
"https://localhost:44301/identity/connect/token",
"mvc_service",
"secret");
return await client.RequestClientCredentialsAsync("sampleApi");
}
使用访问令牌,我正在调用WEBAPI
var client = new HttpClient();
client.SetBearerToken(token);
var gg = this.HttpContext;
var json = await client.GetStringAsync("http://localhost:50990/jarvis");
var jsonStr = JArray.Parse(json).ToString();
var model = JsonConvert.DeserializeObject<List<User>>(jsonStr);
web api由身份服务器和IdentityServer提供的资源自动化保护(Thinktecture.IdentityModel.Owin.ResourceAuthorization.WebApi)
APIController如下
[Authorize]
public class AuthorizationController : ApiController
{
[ResourceAuthorize(AuthorizationResources.AdminActions.Create, AuthorizationResources.Admin)]
public async Task<IHttpActionResult> Get()
{
var user = User as ClaimsPrincipal;
List<User> usersList = await GetUsers();
return Json(usersList);
}
}
我的ResourceAuthorize如下
ResourceAuthorize
public class APIAuthorization: ResourceAuthorizationManager
{
public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context)
{
var resource = context.Resource.First().Value;
if (resource == AuthorizationResources.Admin)
{
return CheckAdminAccessAsync(context);
}
if (resource == AuthorizationResources.Editor)
{
return CheckEditorAccessAsync(context);
}
if (resource == AuthorizationResources.Reader)
{
return CheckReaderAccessAsync(context);
}
return Nok();
}
private Task<bool> CheckReaderAccessAsync(ResourceAuthorizationContext context)
{
return Eval(context.Principal.IsInRole("Admin"));
}
private Task<bool> CheckEditorAccessAsync(ResourceAuthorizationContext context)
{
return Eval(context.Principal.IsInRole("Admin"));
}
private Task<bool> CheckAdminAccessAsync(ResourceAuthorizationContext context)
{
return Eval(context.Principal.IsInRole("Admin"));
}
}
我的问题是
如何将声明传递给WEBAPI,以便我可以检查APIAuthorization: 的eval(context.Principal.IsInRole( “管理员”))
这是进行资源授权的正确方法吗?
答案 0 :(得分:0)
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44333/core",
RequiredScopes = new[] { "profile", "openid" },
});**This is what i was looking for , This solved my problem**