//-----------------------------------------------
Well, to require basic authentication you need to return 401 status code. But doing that will cause the current authentication module to execute its default unauthorized handler (for forms authentication, this means redirecting to login page).
I wrote an ActionFilterAttribte to see if I can get the behaviour you want when there's no authentication module installed in web.config.
publicclassRequireBasicAuthentication:ActionFilterAttribute
{
publicoverridevoidOnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
if(String.IsNullOrEmpty(req.Headers["Authorization"]))
{
var res = filterContext.HttpContext.Response;
res.StatusCode=401;
res.AddHeader("WWW-Authenticate","Basic realm=\"Twitter\"");
res.End();
}
}
}
And the controller action :
[RequireBasicAuthentication]
publicActionResultIndex()
{
var cred =System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.Headers["Authorization"].Substring(6))).Split(':');
var user =new{Name= cred[0],Pass= cred[1]};
returnContent(String.Format("user:{0}, password:{1}", user.Name, user.Pass));
}
That action successfully prints the username and password I enter. But I really doubt that's the best way to do this. Do you have no choice except asking for username and password this way?
//------------------------------------------------------------------
var header = request.Headers.FirstOrDefault(h => h.Key.Equals("Authorization"));
//------------------------------------------
using System;
using System.Configuration;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Http;
using log4net;
using Supertext.BL.CustomerManagement;
namespace Supertext.API.Authorization
{
AuthorizeAttribute
{
]);
RequireSsl
{
}
}
}
;
RequireAuthentication
{
}
}
}
/// <summary>
/// For logging with Log4net.
/// </summary>
));
)
{
//actionContext.Request
)
{
;
}
else
{
);
}
}
)
{
);
);
);
//throw new HttpResponseException();
}
//HttpRequestMessage input)
{
)
{
);
;
}
;
];
;
))
{
;
;
}
;
}
)
{
);
)
{
;
}
;
;
}
)
{
// Check this is a Basic Auth header
;
// Pull out the Credentials with are seperated by ':' and Base64 encoded
);
});
;
// Okay this is the credentials
;
}
)
{
// this is the method that does the authentication
//users often add a copy/paste space at the end of the username
();
();
);
)
{
// once the user is verified, assign it to an IPrincipal with the identity name and applicable roles
));
;
}
else
{
))
{
);
}
;
;
}
}
}
}