Session variable still remains null between two different controllers - asp.net-mvc

I have a problem with my MVC project! The goal is to set a session var in order to pass it to all the controllers:
inside my xUserController,
Session["UserId"] = 52;
Session.Timeout = 30;
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
//SessionUserId ="52"
But within the ChatMessageController
[HttpPost]
public ActionResult AddMessageToConference(int? id,ChatMessageModels _model){
var response = new NzilameetingResponse();
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
//...
}
return Json(response, "text/json", JsonRequestBehavior.AllowGet);
}
SessionUserId = ""
So, Why this ? How to set the session variable to be global within all my controllers ??

There can be only two reasons of such behavior: the first one is that your session is over and the second is that you rewrite you session variable from another place in your application.
Wthout any additional code there is nothing to say more.

Here is how I solved the issue
I know this is not the best way to do it but it helped me:
First I have created a base controller as follows
public class BaseController : Controller
{
private static HttpSessionStateBase _mysession;
internal protected static HttpSessionStateBase MySession {
get { return _mysession; }
set { _mysession = value; }
}
}
then I changed all my controllers' codes in other to let them inherit from the Base Controller class.
Then I overrode the "OnActionExecuting" method as below :
public class xUserController : BaseController
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
BaseController.MySession = Session;
base.OnActionExecuting(filterContext);
}
[HttpPost]
public ActionResult LogIn(FormCollection form)
{
//---KillFormerSession();
var response = new NzilameetingResponse();
Session["UserId"] = /*entity.Id_User*/_model.Id_User;
return Json(response, "text/json", JsonRequestBehavior.AllowGet);
}
}
Finally, I've changed the way I call session variables.
string SessionUserId = ((BaseController.MySession != null) && (BaseController.MySession["UserId"] != null)) ? BaseController.MySession["UserId"].ToString() : "";
instead of
string SessionUserId = ((Session != null) && (Session["UserId"] != null)) ? Session["UserId"].ToString() : "";
now it works and my session vars can walk across all controllers.

Related

ASP.NET Core [FromBody] vs MVC 5 binding

I got an MVC 5 application that i'm porting to asp.net Core.
In the MVC application call to controller we're made using AngularJS $resource (sending JSON) and we we're POSTing data doing :
ressource.save({ entries: vm.entries, projectId: vm.project.id }).$promise...
that will send a JSON body like:
{
entries:
[
{
// lots of fields
}
],
projectId:12
}
the MVC controller looked like this :
[HttpPost]
public JsonResult Save(List<EntryViewModel> entries, int projectId) {
// code here
}
How can I replicate the same behaviour with .NET Core since we can't have multiple [FromBody]
you cannot have multiple parameter with the FromBody attibute in an action method. If that is need, use a complex type such as a class with properties equivalent to the parameter or dynamic type like that
[HttpPost("save/{projectId}")]
public JsonResult Save(int projectId, [FromBody] dynamic entries) {
// code here
}
As pointed out in the comment, one possible solution is to unify the properties you're posting onto a single model class.
Something like the following should do the trick:
public class SaveModel
{
public List<EntryViewModel> Entries{get;set;}
public int ProjectId {get;set;}
}
Don't forget to decorate the model with the [FromBody] attribute:
[HttpPost]
public JsonResult Save([FromBody]SaveViewModel model)
{
// code here
}
Hope this helps!
It's still rough but I made a Filter to mimic the feature.
public class OldMVCFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Method != "GET")
{
var body = context.HttpContext.Request.Body;
JToken token = null;
var param = context.ActionDescriptor.Parameters;
using (var reader = new StreamReader(body))
using (var jsonReader = new JsonTextReader(reader))
{
jsonReader.CloseInput = false;
token = JToken.Load(jsonReader);
}
if (token != null)
{
var serializer = new JsonSerializer();
serializer.DefaultValueHandling = DefaultValueHandling.Populate;
serializer.FloatFormatHandling = FloatFormatHandling.DefaultValue;
foreach (var item in param)
{
JToken model = token[item.Name];
if (model == null)
{
// try to cast the full body as the current object
model = token.Root;
}
if (model != null)
{
model = this.RemoveEmptyChildren(model, item.ParameterType);
var res = model.ToObject(item.ParameterType, serializer);
context.ActionArguments[item.Name] = res;
}
}
}
}
}
private JToken RemoveEmptyChildren(JToken token, Type type)
{
var HasBaseType = type.GenericTypeArguments.Count() > 0;
List<PropertyInfo> PIList = new List<PropertyInfo>();
if (HasBaseType)
{
PIList.AddRange(type.GenericTypeArguments.FirstOrDefault().GetProperties().ToList());
}
else
{
PIList.AddRange(type.GetTypeInfo().GetProperties().ToList());
}
if (token != null)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty jProp in token.Children<JProperty>())
{
var pi = PIList.FirstOrDefault(p => p.Name == jProp.Name);
if (pi != null) // If destination type dont have this property we ignore it
{
JToken child = jProp.Value;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, pi.PropertyType);
}
if (!IsEmpty(child))
{
if (child.Type == JTokenType.Object || child.Type == JTokenType.Array)
{
// nested value has been checked, we add the object
copy.Add(jProp.Name, child);
}
else
{
if (!pi.Name.ToLowerInvariant().Contains("string"))
{
// ignore empty value when type is not string
var Val = (string)child;
if (!string.IsNullOrWhiteSpace(Val))
{
// we add the property only if it contain meningfull data
copy.Add(jProp.Name, child);
}
}
}
}
}
}
return copy;
}
else if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
JToken child = item;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, type);
}
if (!IsEmpty(child))
{
copy.Add(child);
}
}
return copy;
}
return token;
}
return null;
}
private bool IsEmpty(JToken token)
{
return (token.Type == JTokenType.Null || token.Type == JTokenType.Undefined);
}
}

MVC 3 Redirect not working

I have a small problem related to action redirecting. I want to prevent users from being able to access information concerning a specific area in the site using an override of the OnActionExecuting in my BaseController class, which is the base class for all my controllers. Method body:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Request.IsAuthenticated && (User as Eagle.Security.EaglePrincipal != null) && Session != null && Session["LastKnownGoodArea"] != null && filterContext.ActionDescriptor.ActionName != "InvalidPermission")
{
var currentArea = Principal.CurrentCenter.CODEFORM_CSE;
if (currentArea != Session["LastKnownGoodArea"].ToString())
RedirectToActionPermanent("InvalidPermission", "Account", new { target = 0, redirectURL = null as string });
else
base.OnActionExecuting(filterContext);
}
}
However, this does not redirect to the specified action. What am I doing wrong? What other approach, if any, would you guys suggest?
Thanks,
Silviu
What Dave commented is right ! In addition this should be the syntax you are looking for :-
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Request.IsAuthenticated && (User as Eagle.Security.EaglePrincipal != null) && Session != null && Session["LastKnownGoodArea"] != null && filterContext.ActionDescriptor.ActionName != "InvalidPermission")
{
var currentArea = Principal.CurrentCenter.CODEFORM_CSE;
if (currentArea != Session["LastKnownGoodArea"].ToString())
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new
{
controller = "InvalidPermission",
action = "Account",
target = 0,
}));
filterContext.Result.ExecuteResult(filterContext);
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
I want to prevent users from being able to access information concerning a specific area in the site using an override of the OnActionExecuting in my BaseController class, which is the base class for all my controllers.
Why did you choose to use OnActionExecuting for this? You're executing this if-statement on every request, I would recommend to use the Authorize attribute for the specific actions:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var user = User as Eagle.Security.EaglePrincipal;
if(httpContext.User.Identity.IsAuthenticated && user != null)
{
var currentArea = Principal.CurrentCenter.CODEFORM_CSE;
var lastKnownArea = Session["LastKnownGoodArea"];
if (lastKnowArea == null)
return false;
return currentArea.Equals(lastKnownArea.ToString());
}
return base.AuthorizeCore(httpContext);
}
}
In your web.config you can configure redirects like:
<customErrors mode="RemoteOnly">
<error statusCode="403" redirect="/InvalidPermission/Account" />
</customErrors>
If you want control over the UnAuthorized request you can always choose to override the HandleUnauthorizedRequest method
Here is the final solution:
var currentArea = Principal.CurrentCenter.CODEFORM_CSE;
if (currentArea != Session["LastKnownGoodArea"].ToString())
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new
{
controller = "Account",
action = "InvalidPermission",
area = "",
target = 0,
redirectURL = ""
}));
}
else
{
base.OnActionExecuting(filterContext);
}
Thank you both for your input, you helped alot!
Cheers!
You can't redirect to Action from a filter because it is not creating an Action Result yet. You can only create a new route. I'm not completely sure of syntax you need. I threw this together as an example of way to go.
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Request.IsAuthenticated && (User as Eagle.Security.EaglePrincipal != null) && Session != null && Session["LastKnownGoodArea"] != null && filterContext.ActionDescriptor.ActionName != "InvalidPermission")
{
var currentArea = Principal.CurrentCenter.CODEFORM_CSE;
if (currentArea != Session["LastKnownGoodArea"].ToString())
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary {
{"controller", "InvalidPermission"}, {"action", "Account"}, {target =0}, {redirectURL = null as string }
else
base.OnActionExecuting(filterContext);
}
}

Session is null in HttpHandler but not in MVC Controller

I have security in my MVC application set up with an authorize attribute...
public class UserLoggedInAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session["UserId"] == null)
{
var values = new { controller = "Home", action = "Index" };
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(values));
}
}
}
Then I also have a .ashx HttpHandler which is called by jQuery upload control....
public class UploadFile : IHttpHandler, IReadOnlySessionState
{
...
private bool EnsureSecureTransaction(HttpContext context)
{
if (context.Session["UserId"] == null)
{
return false;
}
else
{
return true;
}
return true;
}
}
When EnsureSecureTransaction() gets called the session is coming back null. But session that is read in my MVC action its not. I notice that I'm taking session from the filterContext though.
I have tried to change all the code to try and reference HttpContext.Current.Session like this
[HttpPost]
public ActionResult Logon(AdminModel model)
{
if (model.UserName == "x" && model.Password == "x")
{
HttpContext.Session["UserId"] = "true";
return RedirectToAction("CreateBlog", "Blog");
}
return View;
}
private bool EnsureSecureTransaction(HttpContext context)
{
if (context.Session["UserId"] == null)
{
return false;
}
else
{
return true;
}
return true;
}
But basically when I hit the EnsureSecureTransaction() block its still saying my Session["UserId"] is null and therefor not autehenticating the call to the .ashx file correctly.
Anyone know why this is? Whats the actual difference between AuthorizationContext and HttpContext with regards to the session they carry and how do I get round this problem?

How to get parameter in OnActionExecuting?

I modify the default route rule a little bit as below:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id= (string)null } // Parameter defaults
);
Then I can set url as:
/Controller/Action/myParam
/Home/Index/MyParam
The default Action Index would be:
public ActionResult Index(string id)
{
//....
}
I can get the param in action. But I want to get the param in OnActionExecuting. How can I do it?
You should be able to access it with :
public override void OnActionExecuting(ActionExecutingContext filterContext) {
string id = filterContext.RouteData.Values["id"];
//...
}
It can be accessible from ActionArguments inside OnActionExecuting.
public override void OnActionExecuting(ActionExecutingContext context) {
string id = context.ActionArguments["id"].ToString();
//...
}
if you want to get controller, action, and all parameters, you can do this
var valuesStr = new StringBuilder();
if (ctx.RouteData != null && ctx.RouteData.Values != null)
foreach (var v in ctx.RouteData.Values)
valuesStr.AppendFormat("/{0}", v.Value);
_logger.Info("executing {0}", valuesStr.ToString());
which results in the whole path
results with:
"/Get/Customer/215840"
it should work on multiple parameters just as well.
I use the following code to retrieve and compare the parameters passed to an action (.net core 3.1).
var vals = filterContext.ActionArguments.Values;
var fistobj = vals.FirstOrDefault();
var val = fistobj.GetType().GetProperties().FirstOrDefault(x => string.Equals(x.Name, "nameParameter", StringComparison.OrdinalIgnoreCase)).GetValue(fistobj);
if (val == null || val.ToString() != "value parameter")
{
filterContext.Result = new JsonResult(ExecuteResult.Fail(JanException.Parameter.API00001));
//base.OnActionExecuting(filterContext);
return;
}
More details for OnActionExecuting and a custom Attribute InitializingActionAttribute
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ControllerActionDescriptor controlActionDescriptor = (ControllerActionDescriptor)filterContext.ActionDescriptor;
var attributes = controlActionDescriptor.MethodInfo.CustomAttributes;
if (attributes.Any(a => a.AttributeType == typeof(InitializingActionAttribute)))
{
var vals = filterContext.ActionArguments.Values;
var fistobj = vals.FirstOrDefault();
var val = fistobj.GetType().GetProperties().FirstOrDefault(x => string.Equals(x.Name, "nameParameter", StringComparison.OrdinalIgnoreCase)).GetValue(fistobj);
if (val == null || val.ToString() != "value parameter")
{
filterContext.Result = new JsonResult(ExecuteResult.Fail(JanException.Parameter.API00001));
//base.OnActionExecuting(filterContext);
return;
}
}
base.OnActionExecuting(filterContext);
}
From your filterContext you should be able to get whatever you need.
public class MyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Do your stuff here
}
}
[MyAttribute]
public ActionResult Index(string id)
{
//....
}

Stuck creating a "security trimmed" html.ActionLink extension method

I'm trying to create an Extension Method for MVC's htmlHelper.
The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action.
Borrowing from the MVCSitemap
code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink.
When I try to get the MvcHandler, I get a null value.
Is there a better way to the the attributes for the controller/action?
Here is the code for the extension method:
public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller)
{
//simplified for brevity
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action,controller);
}
else
{
return String.Format("<span>{0}</span>",linkText);
}
}
public static bool IsAccessibleToUser(string action, string controller)
{
HttpContext context = HttpContext.Current;
MvcHandler handler = context.Handler as MvcHandler;
IController verifyController =
ControllerBuilder
.Current
.GetControllerFactory()
.CreateController(handler.RequestContext, controller);
object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true);
if (controllerAttributes.Length == 0 && actionAttributes.Length == 0)
return true;
IPrincipal principal = handler.RequestContext.HttpContext.User;
string roles = "";
string users = "";
if (controllerAttributes.Length > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Length > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role != "*" && !principal.IsInRole(role)) return false;
}
foreach (string user in usersArray)
{
if (user != "*" && (principal.Identity.Name == "" || principal.Identity.Name != user)) return false;
}
return true;
}
}
Here is the working code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Mvc;
using System.Collections;
using System.Reflection;
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false);
}
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled)
{
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action, controller);
}
else
{
return showDisabled ? String.Format("<span>{0}</span>", linkText) : "";
}
}
public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize)
{
Assembly assembly = Assembly.GetExecutingAssembly();
GetControllerType(controllerAuthorize);
Type controllerType = GetControllerType(controllerAuthorize);
var controller = (IController)Activator.CreateInstance(controllerType);
ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));
ArrayList actionAttributes = new ArrayList();
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);
if ((attributes.Length == 0 && method.Name == actionAuthorize) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionAuthorize))
{
actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));
}
}
if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)
return true;
IPrincipal principal = HttpContext.Current.User;
string roles = "";
string users = "";
if (controllerAttributes.Count > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Count > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in usersArray)
{
if (user == "*" && (principal.Identity.Name == user))
return true;
}
return false;
}
public static Type GetControllerType(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType.Name == "Controller" && (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())))
{
return type;
}
}
return null;
}
}
}
I don't like using reflection, but I can't get to the ControllerTypeCache.
Your ViewPage has a reference to the view context, so you could make it an extension method on that instead.
Then you can just say if Request.IsAuthenticated or Request.User.IsInRole(...)
usage would be like <%= this.SecurityLink(text, demandRole, controller, action, values) %>
I really liked the code from #Robert's post, but there were a few bugs and I wanted to cache the gathering of the roles and users because reflection can be a little time costly.
Bugs fixed: if there is both a Controller attribute and an Action attribute, then when the roles get concatenated, an extra comma doesn't get inserted between the controller's roles and the action's roles which will not get analyzed correctly.
[Authorize(Roles = "SuperAdmin,Executives")]
public class SomeController() {
[Authorize(Roles = "Accounting")]
public ActionResult Stuff() {
}
}
then the roles string ends up being SuperAdmin,ExecutivesAccounting, my version ensures that Executives and Accounting is separate.
My new code also ignores Auth on HttpPost actions because that could throw things off, albeit unlikely.
Lastly, it returns MvcHtmlString instead of string for newer versions of MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Collections;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Security.Principal;
public static class HtmlHelperExtensions
{
/// <summary>
/// only show links the user has access to
/// </summary>
/// <returns></returns>
public static MvcHtmlString SecurityLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled = false)
{
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action, controller);
}
else
{
return new MvcHtmlString(showDisabled ? String.Format("<span>{0}</span>", linkText) : "");
}
}
/// <summary>
/// reflection can be kinda slow, lets cache auth info
/// </summary>
private static Dictionary<string, Tuple<string[], string[]>> _controllerAndActionToRolesAndUsers = new Dictionary<string, Tuple<string[], string[]>>();
private static Tuple<string[], string[]> GetAuthRolesAndUsers(string actionName, string controllerName)
{
var controllerAndAction = controllerName + "~~" + actionName;
if (_controllerAndActionToRolesAndUsers.ContainsKey(controllerAndAction))
return _controllerAndActionToRolesAndUsers[controllerAndAction];
Type controllerType = GetControllerType(controllerName);
MethodInfo matchingMethodInfo = null;
foreach (MethodInfo method in controllerType.GetMethods())
{
if (method.GetCustomAttributes(typeof(HttpPostAttribute), true).Any())
continue;
if (method.GetCustomAttributes(typeof(HttpPutAttribute), true).Any())
continue;
if (method.GetCustomAttributes(typeof(HttpDeleteAttribute), true).Any())
continue;
var actionNameAttr = method.GetCustomAttributes(typeof(ActionNameAttribute), true).Cast<ActionNameAttribute>().FirstOrDefault();
if ((actionNameAttr == null && method.Name == actionName) || (actionNameAttr != null && actionNameAttr.Name == actionName))
{
matchingMethodInfo = method;
}
}
if (matchingMethodInfo == null)
return new Tuple<string[], string[]>(new string[0], new string[0]);
var authAttrs = new List<AuthorizeAttribute>();
authAttrs.AddRange(controllerType.GetCustomAttributes(typeof(AuthorizeAttribute), true).Cast<AuthorizeAttribute>());
var roles = new List<string>();
var users = new List<string>();
foreach(var authAttr in authAttrs)
{
roles.AddRange(authAttr.Roles.Split(','));
users.AddRange(authAttr.Roles.Split(','));
}
var rolesAndUsers = new Tuple<string[], string[]>(roles.ToArray(), users.ToArray());
try
{
_controllerAndActionToRolesAndUsers.Add(controllerAndAction, rolesAndUsers);
}
catch (System.ArgumentException ex)
{
//possible but unlikely that two threads hit this code at the exact same time and enter a race condition
//instead of using a mutex, we'll just swallow the exception when the method gets added to dictionary
//for the second time. mutex only allow single worker regardless of which action method they're getting
//auth for. doing it this way eliminates permanent bottleneck in favor of a once in a bluemoon time hit
}
return rolesAndUsers;
}
public static bool IsAccessibleToUser(string actionName, string controllerName)
{
var rolesAndUsers = GetAuthRolesAndUsers(actionName, controllerName);
var roles = rolesAndUsers.Item1;
var users = rolesAndUsers.Item2;
IPrincipal principal = HttpContext.Current.User;
if (!roles.Any() && !users.Any() && principal.Identity.IsAuthenticated)
return true;
foreach (string role in roles)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in users)
{
if (user == "*" && (principal.Identity.Name == user))
return true;
}
return false;
}
public static Type GetControllerType(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType.Name == "Controller" && (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())))
{
return type;
}
}
return null;
}
}

Resources