2013-10-18 73 views
4

我有以下代碼來設置通用主體。Web Api 2基本身份驗證通用主體未設置

public class AuthenticationHandler: DelegatingHandler 
{ 
    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
                        CancellationToken cancellationToken) 
    { 
     var accessToken = request.Headers.Authorization; 
     if (accessToken == null) 
      return base.SendAsync(request, cancellationToken); 

     // Catch an error with regards to the accessToken being invalid 
     try 
     { 
      var formsAuthenticationTicket = FormsAuthentication.Decrypt(accessToken.Parameter); 

      if (formsAuthenticationTicket == null) 
       return base.SendAsync(request, cancellationToken); 

      var data = formsAuthenticationTicket.UserData; 
      var userData = JsonConvert.DeserializeObject<LoginRoleViewModel>(data); 

      var identity = new GenericIdentity(userData.Id.ToString(), "Basic"); 

      var userRole = userData.Roles.ToArray(); 
      var principal = new GenericPrincipal(identity, userRole); 
      Thread.CurrentPrincipal = principal; 
      HttpContext.Current.User = principal; 

     } 
     catch (Exception ex) 
     { 
      var responseMessage = request.CreateResponse(HttpStatusCode.BadRequest, new { ex.Message }); // return ex for full stacktrace 
      return Task<HttpResponseMessage>.Factory.StartNew(() => responseMessage); 
     } 

     return base.SendAsync(request, cancellationToken); 
    } 

} 

下面是一個控制器

[Authorize(Roles = "Administrator, Customers")] 
[HttpGet("customers/{id}")] 
public CustomerViewModel GetCustomer(string id) 
{ 
    var param = AuthService.CheckPermission(Request, User, id); 
    var customer = Db.Customers.Find(param); 
    return Mapper.Map<CustomerViewModel>(customer); 
} 

的例子,這是我檢查,如果用戶角色

public int CheckPermission(HttpRequestMessage request, IPrincipal user, string param) 
{ 
    if (user.IsInRole("Customers") || user.IsInRole("Dealerships")) 
    { 
     if (param == null || param != "me") 
      throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.Forbidden, "unauthorized request")); 
     param = user.Identity.Name; 
    } 

    return Convert.ToInt32(param); 
} 

這是升級到網絡API 2和MVC前工作完美5?現在用戶沒有角色或身份,有什麼變化,我不知道?

回答

8

不知道爲什麼它不工作了,但是在網絡API 2,還有一類新的HttpRequestContextPrincipal財產,那是你應該設置更新Principal。您可以從請求中訪問上下文對象。

+0

這是從的WebAPI遷移到的WebAPI 2 – Matthew

+0

至於他們改變了它的原因後,我的問題,這是由於只從IIS,此舉也支持OWIN。請參閱:http://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/ –

0

更改 「基本」,以 「表單」

var identity = new GenericIdentity(userData.Id.ToString(), "Forms"); 

此外,您使用FormsAuthenticationModule? MVC5支持通過此模塊進行表單身份驗證。檢查這裏給出的示例 http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationmodule.aspx

它建議使用FormsAuthentication_OnAuthenticate進行描述和分配標識。

而且審查http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx

5

真的,爲什麼這個功能已經經過多年的穩定變化不定。

我們發現了以下工作

request.GetRequestContext().Principal = new GenericIdentity(userData.Id.ToString(), "Basic"); 

這也適用和國際海事組織更美觀,你不是要設置一個成員函數

HttpContext.Current.User = new GenericIdentity(userData.Id.ToString(), "Basic"); 
+0

這非常有幫助。感謝您發佈此信息。這不是我所做的。我會在下面發帖。 –

2

這是我做過什麼來得到它加工。升級造成這個問題多麼不幸。

var identity = new GenericIdentity("ApiUser", request.Headers.Authorization.Scheme); 
var principal = new GenericPrincipal(identity, new string[0]);        
request.GetRequestContext().Principal = principal;