1

I have a controller which loads an article and shows it. The article has a property that shows if it is private or public.

If the article is private, I would like the user to log in before showing the article.

I cant just simply put an [Authorize] attribute on the action since if the article is public it shouldn't require authorization to show it.

What would be the most dry way to do this?

I would like to depend on the built in functionality of the default authorization model (I wouldn't want to write redirects and passing parameters manually if I don't need to)

vinczemarton
  • 7,756
  • 6
  • 54
  • 86

1 Answers1

3

What would be the most dry way to do this?

Write a custom authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var articleId = httpContext.Request["id"] as string;
        var article = SomeRepository.GetArticle(id);
        // You can also correlate the article with the currently 
        // connected user and see if it belongs to him, ...
        return article.IsPublic;
    }
}

and then decorate your action with this custom attribute.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This looks good, but I would need to check if the user is logged in as well. – vinczemarton Apr 01 '11 at 15:27
  • I made a followup question please help there too: http://stackoverflow.com/questions/5549371/using-action-parameters-in-custom-authorization-attribute-in-asp-net-mvc3 – vinczemarton Apr 05 '11 at 14:38