/// <summary> /// Determines whether access for this particular request is authorized. This method uses the user <see cref="IPrincipal"/> /// returned via <see cref="HttpRequestContext.Principal"/>. Authorization is denied if the user is not authenticated, /// the user is not in the authorized group of <see cref="Users"/> (if defined), or if the user is not in any of the authorized /// <see cref="Roles"/> (if defined). /// </summary> /// <param name="actionContext">The context.</param> /// <returns><c>true</c> if access is authorized; otherwise <c>false</c>.</returns> protected virtual bool IsAuthorized(HttpActionContext actionContext) { if (actionContext == null) { throw Error.ArgumentNull("actionContext"); } List <string> permittedRoles = WebMethodRoles(actionContext.ActionDescriptor.ControllerDescriptor.ControllerName + "." + actionContext.ActionDescriptor.ActionName); IPrincipal user = actionContext.ControllerContext.RequestContext.Principal; if (user == null || user.Identity == null || !user.Identity.IsAuthenticated) { return(false); } else { int userId = 0; userId = user.Identity.GetUserId <int>(); if (userId != 0) { AtrakModel db = new AtrakModel(); var currentRoles = db.AspNetUsers.First(x => x.Id == userId).AspNetRoles.ToList(); List <string> userRoles = db.AspNetUsers.First(x => x.Id == userId).AspNetRoles.Select(x => x.Name).ToList(); if (userRoles.Intersect(permittedRoles).Any()) { return(true); } } return(false); } }
/// <summary> /// /// </summary> /// <param name="methodName"></param> /// <returns></returns> private List <string> WebMethodRoles(string methodName) { List <string> permittedRoles = new List <string>(); try { using (AtrakModel db = new AtrakModel()) { if (db.WebServiceActions.Where(w => w.Method == methodName).Any()) { permittedRoles = db.WebServiceActions.Where(w => w.Method == methodName).Select(x => x.AspNetRoles.Select(y => y.Name)).Single().ToList(); } else { WebServiceAction wsa = new WebServiceAction(); wsa.Method = methodName; db.WebServiceActions.Add(wsa); db.SaveChanges(); } } } catch (Exception ex) { logger.Error("Authorization Request: WebMethodRoles() ", ex); } return(permittedRoles); }