2016-11-28 62 views
1

我有一個WebAPI項目,我需要爲用戶使用Windows身份驗證,但爲路徑上方的授權屬性實現自定義角色提供程序。但是,當我實施它時,我總是會得到{「消息」:「授權已被拒絕接收此請求。」}作爲我的呼叫結果。而且沒有我的斷點曾經引發除了一個在自定義角色提供在Web API中使用Windows身份驗證的自定義RoleProvider

控制器

[Authorize(Roles="Administrator")] 
[RoutePrefix("api/Constituents")] 
public class ConstituentsController : ApiController 
{ 
[Route("Constituents")] 
    [HttpGet] 
    public IDataResponse<List<IConstituent>> GetConstituents() 
    { 
     return service.GetConstituent(); 
    } 

自定義角色提供

public class CustomRoleProvider : RoleProvider 
{ 
    public CustomRoleProvider() 
    { 
     this.UserRepo = new UserRepository(); //Breakpoint here triggers 
     this.RoleRepo = new RoleRepository(); 
    } 
    public override string[] GetRolesForUser(string username) 
    { 
     var roles = UserRepo.GetUser(username)?.Roles?.Select(r => r.Name).ToArray(); 
     return roles; 
    } 
    public override bool IsUserInRole(string username, string roleName) 
    { 
     var user = UserRepo.GetUser(username); 
     return user.Roles.Select(r => r.Name).Contains(roleName); 
    } 

Web配置

<authentication mode="Windows"/> 
    <roleManager cacheRolesInCookie="false" 
     defaultProvider="CustomRoleProvider" 
     enabled="true"> 
<providers> 
    <clear /> 
    <add name="CustomRoleProvider" 
     type="Data.CustomRoleProvider, Data" /> 
</providers> 

的構造

我錯過了什麼?我需要讓當前用戶發出請求,然後檢查數據庫中是否有適當的角色。

感謝

回答

3

默認情況下,Visual Studio中設置你的項目爲禁用的Windows身份驗證屬性。在屬性窗格中(不是選項卡),您需要將該屬性翻轉爲已啓用。這應該讓你擊中你的RoleProvider的斷點。

Setting Windows Authentication Property in Visual Studio

當你把你的應用程序在服務器上,您可能需要在IIS中執行一個類似的過程,以啓用Windows身份驗證和禁用匿名身份驗證。