Skip to content

Instantly share code, notes, and snippets.

@cobysy
Created April 29, 2016 19:39
Show Gist options
  • Save cobysy/6fc899d95ce432f741179ec2c9daa844 to your computer and use it in GitHub Desktop.
Save cobysy/6fc899d95ce432f741179ec2c9daa844 to your computer and use it in GitHub Desktop.
Custom AuthorizeAttribute to auth swagger
/// <summary>
/// PermissionsAttribute class
/// </summary>
public class PermissionsAttribute : AuthorizeAttribute
{
/// <summary>
/// Gets called on authorization
/// </summary>
/// <param name="actionContext"></param>
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!IsAuthorized(actionContext))
{
if (actionContext.Request.Headers.Contains(Constants.SwaggerUserId))
{
IEnumerable<string> keys = null;
actionContext.Request.Headers.TryGetValues(Constants.SwaggerUserId, out keys);
ClaimsPrincipalWrapper.SetCurrentPrincipal(GetMockedClaimsPrincipal(((string[])keys)[0]));
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
}
/// <summary>
/// Check if the user is authorized
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return base.IsAuthorized(actionContext);
}
/// <summary>
/// Handle unauthorized request
/// </summary>
/// <param name="actionContext"></param>
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
string errorMessage = Constants.AccessDenied;
ErrorModel<MessagesModel> errorDataModel = new ErrorModel<MessagesModel>();
errorDataModel.Errors = new List<MessagesModel>();
errorDataModel.Errors.Add(new MessagesModel()
{
Message = errorMessage
});
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, errorDataModel);
}
private ClaimsPrincipal GetMockedClaimsPrincipal(string userId)
{
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal();
IList<Claim> claimCollection = new List<Claim>
{
new Claim(ConfigurationInfo.ClaimsUri, userId),
new Claim(ClaimTypes.GivenName, Constants.SwaggerUser)
};
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection);
claimsPrincipal.AddIdentity(claimsIdentity);
return claimsPrincipal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment