Answered

Server-Side Authentication Using a Custom AuthorizeAttribute Annotation

The class below is used to create a custom attribute called AgilityAuthorize that performs server-side authentication for Agility Website Users.

using System.Web;
using System.Web.Mvc;
using Agility.UGC.API.WCF;

namespace MVCSampleSite.Security
{
public class AgilityAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
const string websiteUserTypeName = "Profile";
var cookieName = $"UGC_AUTH_{UGCAPIUtil.Agility_API_Key}{websiteUserTypeName}";

var authenticationCookie = httpContext.Request.Cookies.Get(cookieName);
if (authenticationCookie == null) return false;
var token = HttpUtility.UrlDecode(authenticationCookie.Value);

using (var client = UGCAPIUtil.APIClient)
{
var auth = UGCAPIUtil.GetDataServiceAuthorization(-1);

var auth2 = client.IsAuthenticated(auth, token, websiteUserTypeName);
if (auth2 != null && auth2.ProfileRecordID > 0)
{
//Is Authenticated and has a valid auth object
return true;
}
}

return false;
}
}
}

The main purpose of doing this is to have an easy way of securing controller methods when using the MVC (or similar) framework. This can be done on every method in a controller like so:

using System.Web.Mvc;
using MVCSampleSite.Security;

namespace MVCSampleSite.Controllers
{
[AgilityAuthorize]
public class AdminController : Controller
{
public ActionResult Index()
{
// ...
}
}
}

or done on a method-by-method basis like this:

using System.Web.Mvc;
using MVCSampleSite.Security;

namespace MVCSampleSite.Controllers
{
public class AdminController : Controller
{
[AgilityAuthorize]
public ActionResult Index()
{
// ...
}
}
}

Note: the [AllowAnonymous] annotation can be used on individual controller methods to override an [AgilityAuthorize] annotation that is placed on the controller class definition and allows that individual controller method to be executed, even if an unauthenticated or not-logged-in user accesses it

1

Comments

1 comment
  • Amazing, thanks for sharing!! Looks like a great way to authenticate pages/methods for UGC users.

    0
    Comment actions Permalink

Please sign in to leave a comment.

Didn't find what you were looking for?

New post