Use AuthorizeAttribute And JsonResult Together?

Jan 28, 2011

What is the most straight forward way to use AuthorizeAttribute and JsonResult together so that when the user is not authorized the application returns a Json error rather than a log in page?The two things I am currently considering are extending AuthorizeAttribute or just making a new attribute that implements IAuthorizationFilter.

View 1 Replies


Similar Messages:

MVC :: Use AuthorizeAttribute Without Forms Authentication

Oct 12, 2010

I'm writing an MVC app that is a front-end for an existing system with it's own authentication process. I want to mimic the behavior of forms authentication with the [Authorize] attribute redirecting to a log-on page, but the logged in status is handled completely by API calls to the backend system. What do I need to do for ASP.NET MVC to recognize a user as "authenticated" if I'm not using the Forms authentication system?

View 3 Replies

MVC :: Create A Custom AuthorizeAttribute?

Apr 24, 2010

I have a database where i want to log my user into and for this issue i want to customize the AuthorizeAttribute i am wrong ?? have some easier way to do it ??

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// the "new" must be used here because we are overriding
// the Roles property on the underlying class
public new Authorization.SiteRoles Roles;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
string[] users = Users.Split(',');
if (!httpContext.User.Identity.IsAuthenticated)
return false;
int found = Convert.ToInt32(httpContext.Session["role"]);
return Authorization.CheckRolesCompliance(Roles);
}
}

ERROR: 'CustomAuthorizeAttribute.AuthorizeCore(System.Web.HttpContextBase)': no suitable method found to override

View 4 Replies

Use Custom AuthorizeAttribute In View?

Nov 26, 2010

I Create my won Authorize Attribute. Thats work great in the controller. How can I use it in the view.

Example : I have a manage user link, If you haven't access to this page, I don't want to show the link.

Here is my Authorize Attribute.

public class UserAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["UserID"] == null)

[Code]....

View 1 Replies

MVC :: Creating A Custom AuthorizeAttribute?

Jun 3, 2010

I thought about creating a custom AuthorizeAttribute that will prevent logged in users calling a action ( [UnAuthorized] so to speak)

Tried creating a custom AuthorizeAttribute and override the AuthorizeCore method, but not sure this is the right approach.

(does not work anyhow...get an error telling me "no suitable method found to override")

[Code]....

View 7 Replies

C# - MVC AuthorizeAttribute Passing Values To ActionMethod?

May 14, 2010

I'm only a newcomer to ASP.NET MVC and am not sure how to achieve a certain task the "right way".

Essentially, I store the logged in userId in HttpContext.User.Identity and have written an EnhancedAuthorizeAttribute to perform some custom authorization.

In the overriden OnAuthorization method, my domain model hits the database to ensure the current user id can access the passed in routeValue "BatchCode". The prototype is:

ReviewGroup GetReviewGroupFromBatchCode(string batchCode);

It will return null if the user can't access the ReviewGroup and the OnAuthorization then denies access.

Now, I know the decorated action method will only get executed if OnAuthorization passes, but I don't want to hit the database a second time to get the ReviewGroup again.

I am thinking of storing the ReviewGroup in HttpContext.Items["reviewGroup"] and accessing this from the controller at the moment.

View 3 Replies

Why Would User.IsInRole Return True, But AuthorizeAttribute Not

Jan 25, 2011

I'm securing an ASP.NET MVC 2 application, and I have a user who is in the role "Foo".

This is true:

User.IsInRole("Foo")

But yet, when I attempt to lock down a controller action like the following, the user is denied:

[Authorize(Roles = "Foo")]
public ActionResult PrivatePage()
{
return View();
}

If IsInRole reports true, why would the Authorize attribute not allow the user in?

View 2 Replies

MVC :: Hide/Show Content Using ActionFilterAttribute/AuthorizeAttribute?

Aug 19, 2010

I'm using MVC 2 with futures, and I'm trying to hide/show content based on role. Is there a way with ActionFilterAttribute or AuthorizeAttribute if the authentication fails to not show a partial view on a controller all through attributes? Or is all I can
do with those attributes is redirect or throw up an error message? I just need the child action to return nothing basically if it fails the authentication.

I found a way using ActionFilterAttribute, but it's kind of a hack because it still calls the ChildAction on the controller and then I'm setting the result to empty afterwards. I'm looking for it not to call the Action/ChildAction at all if the authentication fails. Is there a way to restrict that call?

public
override
void OnActionExecuted(ActionExecutedContext [code].....

View 2 Replies

C# - Extend AuthorizeAttribute And Check The User's Roles?

Feb 25, 2011

I am busy writing my own custom attribute for my action method called MyAuthorizeAttribute, I am still busy writing the code, here is my partial code:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public new Role Roles;
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (Roles != 0) // Did it this way to see what the value of Roles was
return;
// Here I am going to get a list of user roles
// I'm doing my own database calls
filterContext.Result = new HttpUnauthorizedResult();
}
}

Here is my Role enum:

public enum Role
{
Administrator = 1,
SuperAdministrator = 2
}

My action method:

[MyAuthorize(Roles = Role.Administrator|Role.SuperAdministrator)]
public ActionResult Create()
{
return View();
}

The reason why I did not use Roles = "Administrator,SuperAdministrator" was because the roles are hard-coded. I don't want to have a 100 places to change if the role name changes.

Given my method, when it gets to if (Roles != 0) then Roles total value is 3, how would I check to see if these 2 roles is in the list of user roles for a specific user?

Am I doing it correct here? If not how would I otherwise implement this? It doesn't have to be the way that I did it in.

View 2 Replies

Json - Get The JsonResult In Function?

Jan 31, 2011

How can I get the result of a method that return a JsonResult and cast into string.

[HttpPost]
public JsonResult AnalyseNbPayment(DateTime dt, DateTime dt2,int FrequencyID) {
if (FrequencyID == ApplConfig.Frequency.WEEKLY) {
return Json(new { val = GetNbWeek(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.MONTHLY) {
return Json(new { val =GetDateDiffInMonth(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.QUARTELY) {
return Json(new { val = GetQuarterLy(dt, dt2) });
}
else if (FrequencyID == ApplConfig.Frequency.BI_MONTLY) {
return Json(new { val = GetBiMontlhy(dt, dt2) });
}
else if(FrequencyID == ApplConfig.Frequency.YEARLY)
{
return Json(new { val = GetNbYear(dt, dt2) });
}
return Json(new { val =0 });
}

I want to call my method like this

string MyValue = AnalyseNbPayment(Convert.ToDateTime(ViewModel.oRent.DateFrom), Convert.ToDateTime(ViewModel.oRent.DateTo), Convert.ToInt32(oLease.FrequencyID)).val.ToString(); <br />

View 1 Replies

MVC :: Read Raw Jsonresult Output?

Sep 5, 2010

How can i get to see the raw jsonresult of an action in a controller? i want to make sure its returning correctly formed data.

View 4 Replies

MVC :: JsonResult Only Returns IEnumerable Data?

Mar 31, 2010

My controller has a member that returns a JsonResult object, it is coded as per below. The problem is that Json(users) only returns the data from IEnumerable (MembershipUserEx objects) and I also want the data from the public Properties of MembershipUserExCollection as well. Is there a way to do this? I guess I am looking for the Json object to look something like this pseudo object:

results = {
pageIndex:0,
pageSize:50,

[code]...

View 1 Replies

Convert A JSON String Into JsonResult?

Apr 21, 2010

I have some stored JSON strings stored in the DB which I want to return to the client as JsonResult . I know that Json(object) turns an object into JsonResult but what if I already have the result in a string ? can I cast it to JsonResult

View 2 Replies

MVC :: Utilize Dynamic Type With JsonResult?

Apr 1, 2011

Is it possible to do something like this inside an action?

[Code]....

View 8 Replies

JsonResult Shows Up A File Download In Browser?

Apr 3, 2010

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:

Javascript:

[Code]....


If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?

View 3 Replies

MVC :: Can JsonResult Method Return Data Table

Jan 16, 2011

I am wondering if jsonResult method can be used to return Data Table? If so, is it a json array or a json string?

View 6 Replies

MVC :: RenderPartial To String For JsonResult While Maintaining Testability?

Mar 28, 2010

I would like to wrap a RenderPartial in a JsonResult so that my jQuery can handle placement/positioning of the html data based on additional Json parameters.

e.g. {html: <string returned from RenderPartial>, typeofdata: 1}

After Googling, it seems that the only way to do this is a workaround that hijacks HttpContext in order to spit the PartialViewResult into a string. However, this seems like it would break testability.

Is JsonResult not intended to be used with RenderPartial?

Alternatively, I could set typeofdata as a parameter of the model, and have the PartialView render it as a hidden field, then have jQuery look for it. What is a better way to generate the data that I need?

View 5 Replies

MVC :: Internal Server Error On JsonResult Return?

Mar 5, 2010

I've got an ActionMethod that returns a JsonResult object and this isn't returning data to the calling jquery function. I have used wget to send and receive raw data to it, and I've discovered that when the object dataset is empty, it returns a value fine and the wget return is

HTTP request sent, awaiting response... 200 OK

Length: 78 [application/json]

Saving to: `filename'

but when there is data in the object dataset I get an internal server error:-

HTTP request sent, awaiting response... 500 Internal Server Error

2010-03-05 13:21:16 ERROR 500: Internal Server Error.

This is a dataset of objects being returned - are there any common "gotchas" when doing this?

View 8 Replies

Jquery - MVC2 JsonResult This Request Has Been Blocked?

Dec 17, 2010

I know the question is very familiar but i can't over it.This is my Controller Action

public JsonResult AddToCart(int productId, int quantity = 1, int optionValue = 0)
{
AjaxActionResponse res = new AjaxActionResponse();

[code]...

View 2 Replies

Show Data In A View By Passing A JsonResult?

Apr 27, 2010

How Can we Show Data in a View By passing a jsonResult?

View 1 Replies

C# - Retrieving Selected Item Text Within A JsonResult Function

Mar 3, 2011

I am creating an MVC project with a table using the JQGrid plugin. I would like to use a DropDownList to allow the user to specify a value, that will be used in an SQL query to retrieve specific data from the table. I.e. user can select a country from the list, and the table will display items only from that country. I cannot figure out how to retrieve the selected item from the DropDownList, within my data bind function for my table, within my controller class.

DropDownList in the View

<%= Html.DropDownList("Countries")%>

Setting up the DropdownList in my controller

//dt is a DataTable which holds the values for my list
List<SelectListItem> countries = new List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count; i++)
[code]....
The problem seems to be that within a JsonResult function I don't have access to the ViewData or my ViewModel, which always seem to be null when I try and access them. I am very new to MVC and web development,

View 2 Replies

MVC :: Using Jsonresult Actions To Pass Json Data To Third Party Apps?

Oct 9, 2010

i want to use MVC 2 actions to pass JSON data to a 3rd party application via a URL.The URL will be in the form of http://www.abc.com/controller/action..I am using JSonResultHow can i test the output of this URL to ensure the JSON is properly formed..

View 2 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved