2016-12-09 7 views

答えて

0

これが機能していることがわかりました。要件にはユーザーの主張の役割をチェックする追加ハンドラが必要であり、コードはこのように見えます。

追加情報がthis MSDN page上またはthis article

私の例では見つけることができます:

public class Startup 
{ 
     public void ConfigureServices(IServiceCollection services) 
     { 
      services.AddAuthorization(options => { 
       options.AddPolicy("IsEducationOwner", policy => 
       { 
        policy.Requirements.Add(new EducationOwnerRequirement()); 
       }); 
      }); 
      services.AddTransient<IAuthorizationHandler, IsEducationOwnerHandler>(); 
      services.AddTransient<IAuthorizationHandler, HasCatalogAdminRoleHandler>(); 
     } 
} 


public class EducationOwnerRequirement : IAuthorizationRequirement 
{ 
} 

public class HasCatalogAdminRoleHandler : AuthorizationHandler<EducationOwnerRequirement> 
{ 

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EducationOwnerRequirement requirement) 
    { 
     if (context.User.IsInRole("CatalogAdmin")) 
     { 
      context.Succeed(requirement); 
     } 
     return Task.CompletedTask; 
    } 
} 

public class IsEducationOwnerHandler : AuthorizationHandler<EducationOwnerRequirement> 
{ 
    private PerformaContext _db; 

    public IsEducationOwnerHandler(PerformaContext db) 
    { 
     _db = db; 
    } 


    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EducationOwnerRequirement requirement) 
    { 
     var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext; 

     if (mvcContext == null || !context.User.HasClaim(c => c.Type == ClaimTypeNaming.oid)) 
     { 
      return Task.CompletedTask; 
     } 
     var path = mvcContext.HttpContext.Request.Path.Value; 
     var educationId = path.Substring(path.IndexOf("/api/educations/") + 16, path.Length - path.IndexOf("/api/educations/") - 16); 
     var userExternalId = context.User.FindFirst(ClaimTypeNaming.oid).Value; 
     var userId = _db.GetUserByExternalId(userExternalId).Select(x => x.Id).FirstOrDefault(); 

     if(userId == Guid.Empty) 
     { 
      return Task.CompletedTask; 
     } 

     var educationOwners = _db.GetOwnersForEducation(Guid.Parse(educationId)).Select(x => x.UserId).ToList(); 

     if (educationOwners.Contains(userId)) 
     { 
      context.Succeed(requirement); 
     } 
     return Task.CompletedTask; 
    } 
} 
+0

または機能がここに文書化されていますhttps://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies#why-would-i-want-a-requirementのための複数のハンドラ – spottedmahn

関連する問題