我有以下代码来设置通用主体。
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);
}
这在升级到 Web Api 2 和 MVC 5 之前工作得很好吗?现在用户没有角色或身份,有什么我不知道的变化吗?