2014-07-10 31 views
5

Tôi đang sử dụng API Web ASP.Net phía sau Xác thực Windows và sử dụng thuộc tính [Ủy quyền] để quyết định những bộ điều khiển và chức năng mà người dùng có quyền truy cập. Điều này làm việc tuyệt vời. Vấn đề là tôi muốn có khu vực trợ giúp chỉ phản ánh những gì người dùng đã được cấp quyền truy cập. Tò mò nếu có ai đã đạt được điều này trong một số thời trang. Điều này được thực hiện ở cấp độ của bộ điều khiển, App Start hay bộ điều khiển trợ giúp.Trang trợ giúp ASP.Net Web Api dựa trên ủy quyền

Cảm ơn trước ...

đoạn mã của một trong các bộ điều khiển của tôi

[Authorize] 
public class TaktTimeController : ApiController 
{ 
    private BIDataContainer db = new BIDataContainer(); 

    // GET api/TaktTime 
    [Authorize(Roles="Admins")] 
    public IQueryable<TaktTime> GetTaktTimes() 
    { 
     return db.TaktTimes; 
    } 

    // GET api/TaktTime/5 
    [ResponseType(typeof(TaktTime))] 
    [Authorize(Roles = "Admins")] 
    public IHttpActionResult GetTaktTime(string id) 
    { 
     TaktTime takttime = db.TaktTimes.Find(id); 
     if (takttime == null) 
     { 
      return NotFound(); 
     } 

     return Ok(takttime); 
    } 

Trả lời

1

này có thể đạt được trong quan điểm dao cạo một cái gì đó như sau sẽ là những gì bạn cần.

@if (User.IsInRole("admin")) 
{ 
    <div> 
     <!--Text for admin here--> 
    </div> 
} 
@if (User.IsInRole("user")) 
{ 
    <div> 
     <!--Text for user here--> 
    </div> 
} 

Logic tương tự có thể được sử dụng trong điều khiển WebAPI

public string Get() 
{ 
    if(User.IsInRole("admin")) 
    { 
     return "Text for admin"; 
    } 

    if(User.IsInRole("user")) 
    { 
     return "Text for user"; 
    } 
} 
1

Bạn sẽ cần phải sửa đổi HelpController.cs và thêm các phương pháp sau đây:

using System.Collections.ObjectModel; 

private Collection<ApiDescription> FilteredDescriptions() 
{ 
    var desctiptionsToShow = new Collection<ApiDescription>(); 

    foreach (var apiDescription in Configuration.Services.GetApiExplorer().ApiDescriptions) 
    { 
     var actionDescriptor = apiDescription.ActionDescriptor as ReflectedHttpActionDescriptor; 
     var authAttribute = actionDescriptor?.MethodInfo.CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == nameof(System.Web.Http.AuthorizeAttribute)); 
     var roleArgument = authAttribute?.NamedArguments?.FirstOrDefault(x => x.MemberName == nameof(System.Web.Http.AuthorizeAttribute.Roles)); 
     var roles = roleArgument?.TypedValue.Value as string; 
     if (roles?.Split(',').Any(role => User.IsInRole(role.Trim())) ?? false) 
     { 
      desctiptionsToShow.Add(apiDescription); 
     } 
    } 
    return desctiptionsToShow; 
} 

Và gọi nó từ Index() hành động:

return View(FilteredDescriptions()); 
Các vấn đề liên quan