Handling expired oAuth token in asp.net mvc - model-view-controller

I created a custom filter class which inherit ActionFilterAttribute
the method looks like below
public override void OnActionExecuting(HttpActionContext actionContext)
{
//my custom code
}
and my controller looks like below
[HttpPost]
[ActionName("Get")]
[Authorize]
[Filters.AuthorizeLogin()]
public List<BusinessEntities.Admin.Role> Get(Dictionary<string, string> Parameters)
{
//My api call
}
but the problem is whenever my token got expired my custom function (OnActionExecuting) did not execute,
I want to execute my custom function even after my token got expired.
and should I use [Authorize] filter when using [Filters.AuthorizeLogin()] filter in my api controller.

Related

how to set up url routing with sub-paths

i am new to webapi and MVC in general. If I wanted to group my service URLs like this
/api/account/create
/api/account/login
/api/account/resetpass
Am I able to put all 3 method calls in the same controller file and somehow map a particular request to the right method?
Create a Controller named Account and Create 3 [GET, POST, PUT, DELETE] method and name them create , login ,resetpass.
By Default, this is the routing for MVC / API(Id can be optional)
route Template: "api/{controller}/{id}",
Example :
public class AccountController : ApiController
{
[HttpPost]
public string Create()
{
// CODE
}
[HttpPost] // or [HttpGet]
public string Login ()
{
// CODE
}
[HttpPost]
public string Resetpass()
{
// CODE
}
}
if you had trouble calling them, try to give them a specific route :
[HttpGet("GetSubject/{subject}")]
public int GetSubjectId(String subject)
{
//CODE
}
Please if you get any error or misunderstanding, don't hesitate to post a comment

Custom Authorization - Web Api

I have a web api for which i would need to implement custom authentication and authorization. The authorization should be defined by Resource and Action as shown below:
[Authorize("users","view")]
public async Task<IHttpActionResult> GetAsync()
{
}
Is there any way i can use custom authorization filter and implement this?
Also, the web api is protected by client certificate and the caller is identifier by key which is passed in the request header. The Key is authenticated using a custom authentication filter.
Regarads,
John
Yes you can create custom Authorization and put on controller or method that needs to be authorized.
sample example is as below
public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
private string Resource { get; set; }
private string Action { get; set; }
public CustomAuthorize(string resource, string action)
{
Resource = resource;
Action = action;
}
public override void OnAuthorization(
System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
//Check your post authorization logic using Resource and Action
//Your logic here to return authorize or unauthorized response
}
}
Here you can do your custom authorization logic and sample controller will look like this
public class DoThisController : ApiController
{
[CustomAuthorize("users","view")]// for specific methods
public string Get()
{
return "Sample Authorized";
}
}

web api 2 controller multiple post methods

I have a controller with the default post method. I want to add one more with a different name and action. The problem is when I make the request POST (http://localhost:57926/api/Users/Login) it doesn't execute Login method, it executes the default PostUser method.
How can I fix this?
// POST: api/Users
[ResponseType(typeof(User))]
public IHttpActionResult PostUser(User user){
//Some code
}
[HttpPost]
[Route("Login")]
public IHttpActionResult Login(JObject form)
{
//some code
}

global authorization not working - results in blank page rendered

I am trying to implement a very basic login scheme for my MVC3 site. If I understand correctly, instead of adding the [Authorize] markup to each of my controller classes, I should be able to simply implement a global setting. To accomplish this, I have added the following into global.asax:
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
and in my webconfig, I added:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
The result is that the resulting page is totally blank. Looking at the url, it seems that mvc is redirecting to my login route as expected except the page empty. If I comment out the code in global.asax and just place the [Authorize] markup directly in each contoller, it works as expected.
As a workaround, I have implemented what I have read the MVC2 best practice to be, which was to create a BaseController:Controller class, add the [Authorize] markup to it, and then change the inherentences of all of my controllers to inheret from BaseController instead of Controller.
That seems to work well enough for now.
But why isn't the global.asax implementation working?
Let's see what's happening here:
You are navigating to /
Your global authorize attribute kicks in and since the user is not authenticated he is redirected to ~/Account/LogOn (as instructed in your web.config file) for authentication
Your global authorize attribute kicks in and since the user is not authenticated he is redirected to ~/Account/LogOn (as instructed in your web.config file) for authentication
Same as 3.
Same as 4.
...
I think you get the point. The LogOn action should be excluded from authentication otherwise the user can never get a chance to login to your web site.
Since you have applied the Authorize attribute globally this cannot be done. One possible way is to write a custom AuthorizeAttribute that will be applied globally and which will exclude this action from authentication.
So you could write a marker attribute:
public class AllowAnonymousAttribute : Attribute
{
}
and a global custom authorize attribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var exclude = ((AllowAnonymousAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false)).Any();
if (!exclude)
{
base.OnAuthorization(filterContext);
}
}
}
that will be registered:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyAuthorizeAttribute());
}
Now all that's left for you is to decorate the controller actions that you want to be excluded from authentication with our marker attribute:
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult LogOn()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
...
}
}

Apply AuthorizeAttribute to a controller class and to action simultaneously

Is There one way to make a [Authorize] attibute be ignored in one action in a controller class that has a Authorize attribute?
[Authorize]
public class MyController : Controller
{
[Authorize(Users="?")]//I tried to do that and with "*", but unsuccessfuly,
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod()
{
//some code
}
}
Just the PrivateMethod() should have authentication required, but it has been required too.
PS: I wouldn't like to make my custom authorize filter.
[]'s
You can use [AllowAnonymous]
[Authorize]
public class MyController : Controller
{
[AllowAnonymous]
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod()
{
//some code
}
}
By default it's impossible - if you set [Authorize] for controller then only authenticated user can access to action.
or
You can try custom decisions: stackoverflow.
A solution is in this article: Securing your ASP.NET MVC 3 Application
The article talks about a white list approach where you decorate actions with a AllowAnonymous custom attribute. It requires that you extend AuthorizeAttribute and the OnAuthorization method to skip authorization checks of AllowAnonymous -actions. (The approach is credited to Levi, a security expert on the MVC team.)
public class MyController : Controller
{
[Authorize] //it will only work for the following action
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod() //[Authorize] will not work for this action
{
//some code
}
}
Just for future reference This is now available to be done by the the [AllowAnonymous] attribute in ASP.NET MVC 4.
More Info

Resources