我有以下代碼來設置通用主體。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?現在用戶沒有角色或身份,有什麼變化,我不知道?
這是從的WebAPI遷移到的WebAPI 2 – Matthew
至於他們改變了它的原因後,我的問題,這是由於只從IIS,此舉也支持OWIN。請參閱:http://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/ –