Calling webapi only when client has install certificate in his machine - asp.net

I wanwt to add a layer of security via certificate to access a hosted ASP.NET WebAPI.
I want only those clients who have installed the certificate in their machine to have access to that WebAPI.
Can anyone provide me a way to achieve this behavior?

You can configure IIS to require client certificates without writing a single line of code. Just follow these instructions, specifically these:
Click SSL settings in the middle panel and select Require SSL and Require for Client certificates.
Double click the Authentication icon and disable all the Authentication method.
Make sure the IIS Client Certificate Mapping Authentication is installed.
Click the Configuration Editor in the middle panel and set the one to one mappings refer to this link

Just as suggested in comments, a quick google search could lead to interesting results.
Nevertheless a possible solution is the implementation proposed in the following Microsoft article :
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
base.OnAuthorization(actionContext);
}
}
}
You would then decorate your ApiController action :
public class SomeController : ApiController
{
[RequireHttps]
public HttpResponseMessage Get() { ... }
}

Related

Can I have application listening in multiple ports? (one for public and one for private use)

I have a .NET MVC application which has multiple features.
Can I host this application in IIS as single application by configuring different ports as shown below?
Website to view product localhost:80/index.cs
API exposed for internal usage localhost:23004/Listporducts();
Is it possible?
Real time scenario: I am hosting application in Azure IaaS VM. My internal applications will use the API and customers shall use public website
In my opinion, the most easily thing is you could prevent the Azure VM's not open the 23004 port. Details, you could refer to this article.
If you don't want to use Azure MV, you could consider using a custom filter Attribute in the web api to check if the request is local. If the request is not sent from local, then you could directly return the 404 not found error.
More details about how to use custom Filter Attribute, you could refer to this article.
public class CustomActionAttribute : FilterAttribute, IActionFilter {
public void OnActionExecuting(ActionExecutingContext filterContext) {
if (filterContext.HttpContext.Request.IsLocal) {
filterContext.Result = new HttpNotFoundResult();
}
}
public void OnActionExecuted(ActionExecutedContext filterContext) {
// not yet implemented
}
}

How to Customize ASP.NET Web API AuthorizeAttribute for Unusual Requirements

I am inheriting from System.Web.Http.AuthorizeAttribute to create a custom authorization/authentication routine to meet some unusual requirements for a web application developed using ASP.NET MVC 4. This adds security to the Web API used for Ajax calls from the web client. The requirements are:
The user must logon each time they perform a transaction to verify
someone else has not walked up to the workstation after someone has
logged on and walked away.
Roles cannot be assigned to the web service methods at program time.
They must be assigned at run time so that an administrator can
configure this. This information is stored in the system database.
The web client is a single page application (SPA) so the typical forms authentication does not work so well, but I am trying reuse as much of the ASP.NET security framework as I can to meet the requirements. The customized AuthorizeAttribute works great for requirement 2 on determining what roles are associated with a web service method. I accept three parameters, application name, resource name and operation to determine which roles are associated with a method.
public class DoThisController : ApiController
{
[Authorize(Application = "MyApp", Resource = "DoThis", Operation = "read")]
public string GetData()
{
return "We did this.";
}
}
I override the OnAuthorization method to get the roles and authenticate the user. Since the user has to be authenticated for each transaction I reduce the back and forth chatter by performing authentication and authorization in the same step. I get the users credentials from the web client by using basic authentication which passes the encrypted credentials in the HTTP header. So my OnAuthorization method looks like this:
public override void OnAuthorization(HttpActionContext actionContext)
{
string username;
string password;
if (GetUserNameAndPassword(actionContext, out username, out password))
{
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
base.Roles = GetResourceOperationRoles();
}
else
{
FormsAuthentication.SignOut();
base.Roles = "";
}
}
else
{
FormsAuthentication.SignOut();
base.Roles = "";
}
base.OnAuthorization(actionContext);
}
GetUserNameAndPassword retrieves the credentials from the HTTP header. I then use the Membership.ValidateUser to validate the credentials. I have a custom membership provider and role provider plugged in to hit a custom database. If the user is authenticated I then retrieve the roles for the resource and operation. From there I use the base OnAuthorization to complete the authorization process. Here is where it breaks down.
If the user is authenticated I use the standard forms authentication methods to log the user in (FormsAuthentication.SetAuthCookie) and if they fail I log them out (FormsAuthentication.SignOut). But the problem seems to be that base OnAuthorization class does not have access to Principal that is updated so that IsAuthenticated is set to the correct value. It is always one step behind. And my guess is that it is using some cached value that does not get updated until there is a round trip to the web client.
So all of this leads up to my specific question which is, is there another way to set IsAuthenticated to the correct value for the current Principal without using cookies? It seems to me that cookies do not really apply in this specific scenario where I have to authenticate every time. The reason I know IsAuthenticated is not set to the correct value is I also override the HandleUnauthorizedRequest method to this:
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
{
if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated)
{
filterContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
This allows me to return a status code of Forbidden to the web client if the failure was because of authorization instead of authentication and it can respond accordingly.
So what is the proper way to set IsAuthenticated for the current Principle in this scenario?
The best solution for my scenario appears to be bypass the base OnAuthorization completely. Since I have to authenticate each time cookies and caching the principle are not of much use. So here is the solution I came up with:
public override void OnAuthorization(HttpActionContext actionContext)
{
string username;
string password;
if (GetUserNameAndPassword(actionContext, out username, out password))
{
if (Membership.ValidateUser(username, password))
{
if (!isUserAuthorized(username))
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
}
else
{
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
else
{
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
I developed my own method for validating the roles called isUserAuthorized and I am not using the base OnAuthorization any more since it checks the current Principle to see if it isAuthenticated. IsAuthenticated only allows gets so I am not sure how else to set it, and I do not seem to need the current Principle. Tested this out and it works fine.
Still interested if anyone has a better solution or can see any issues with this this one.
To add to the already accepted answer: Checking current sourcecode (aspnetwebstack.codeplex.com) for System.Web.Http.AuthorizeAttribute, it looks like the documentation is out of date. Base OnAuthorization() just calls/checks private static SkipAuthorization() (which just checks if AllowAnonymousAttribute is used in context to bypass the rest of the authentication check). Then, if not skipped, OnAuthorization() calls public IsAuthorized() and if that call fails, it then calls protected virtual HandleUnauthorizedRequest(). And that's all it does...
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
if (SkipAuthorization(actionContext))
{
return;
}
if (!IsAuthorized(actionContext))
{
HandleUnauthorizedRequest(actionContext);
}
}
Looking inside IsAuthorized(), that's where Principle is checked against roles and users. So, overriding IsAuthorized() with what you have above instead of OnAuthorization() would be the way to go. Then again, you'd still have to probably override either OnAuthorization() or HandleUnauthorizedRequest() anyway to decide when to return a 401 vs a 403 response.
To add to the absolutely correct answer by Kevin, I'd like to say that I may slightly modify it to leverage the existing .NET framework path for the response object to ensure downstream code in the framework (or other consumers) is not adversely affected by some weird idiosyncrasy that can't be predicted.
Specifically this means using this code:
actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, REQUEST_NOT_AUTHORIZED);
rather than:
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
Where REQUEST_NOT_AUTHORIZED is:
private const string REQUEST_NOT_AUTHORIZED = "Authorization has been denied for this request.";
I pulled that string from the SRResources.RequestNotAuthorized definition in the .NET framework.
Great answer Kevin! I implemented mine the very same way because executing OnAuthorization in the base class made no sense because I was verifying an HTTP Header that was custom to our application and didn't actually want to check the Principal at all because there wasn't one.

What is the preferred way to access ASP.NET profile in .NET n-tier application?

I have a WPF application which talks to a WCF service hosted in IIS. I am also using ASP.NET authorization and authentication to access the service methods. There is also a relatively thin web based interface to the system as well.
What I want is to make use of the ASP.NET Profiles. For example - load profile from server, make changes and then save back to the server. All that with WCF Service calls.
This is my sample User Profile class which is declared server side. I have also defined the appropriate entries in the web.config so it works properly.
public class UserProfile: ProfileBase
{
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
public int? XMLVersion
{
get
{
return this["XMLVersion"] as int?;
}
set
{
this["XMLVersion"] = value;
}
}
}
However I cannot pass it back to the client because ProfileBase is not serializable. Of course I can declare data transfer class which will transfer data back and forth from the profile but it does not look as a very good solution.
So far I am unable to find information how to implement it. Can someone help me with that or point me to another solution?
The WCF profile service does what you are asking for. Have a look at it here.
You can see the list of methods it provides in this MSDN page

How to call https asmx web service if certificate has expired in .NET

Asmx web service is called using Visual Studio generated code from MVC2 controller using code below.
Method call throws exception since web service certificate has expired. How to fix this so that web service can still used?
Using .NET 3.5 and MVC2.
public class AsmxController : Controller
{
public ActionResult Index()
{
var cl = new store2.CommerceSoapClient();
// System.ServiceModel.Security.SecurityNegotiationException was unhandled by user code
//Message=Could not establish trust relationship for the SSL/TLS secure channel with authority 'asmxwebservice.com'.
var vl = cl.GetVendorList( AsmxService.LicenseHeader() ,
new AsmxService.GetVendorListRequest());
return View();
}
}
}
From James blog:
So, for testing, we needed to find a way to bypass the certificate
validation. It turns out that you need to provide a
RemoteCertificateValidationCallback delegate and attach it to
ServicePointManager.ServerCertificateValidationCallback. What’s not
clear is what happens if two threads are competing to set this
property to different values, since it’s a static property. Reflector
suggests that the property set method doesn’t do anything fancy, so
you could easily get into a race condition.
so, he does the following:
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(
object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
if (Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreSslErrors"]))
{
// allow any old dodgy certificate...
return true;
}
else
{
return policyErrors == SslPolicyErrors.None;
}
}

How to "un-impersonate" (un-delegate?) in Kerberos

I have a web application using Kerberos to access an external resource useing ASP.NET 3.5 and IIS.
When a user connects with the application, Kerberos authentication auto-magically allows me to connect to external resources acting as the user using delegation. This was not easy to do. It is nice, but I've a problem. Sometimes I need to connect to an external resource using an account with more rights than the user. The service account which the app-pool is running under has the addition rights I need. How can I remove the user's Kerberos identification and connect with Kerberos using the service account running the application pool?
UPDATE
I'm not sure why I am getting no responses at all. I've never seen that before. Please post questions, they may clarify the problem (to me too).
Woring in Kerberos and need an overview of delegation? Read the first part of this answer: https://stackoverflow.com/a/19103747/215752.
I have a class:
public class ProcessIdentityScope : IDisposable
{
private System.Security.Principal.WindowsImpersonationContext _impersonationContext;
private bool _disposed;
public ProcessIdentityScope()
{
_impersonationContext = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_impersonationContext.Undo();
_impersonationContext.Dispose();
_disposed = true;
}
else
throw new ObjectDisposedException("ProcessIdentityScope");
}
#endregion
}
And I use it like so:
using(ProcessIdentityScope identityScope = new ProcessIdentityScope())
{
// Any code in here runs under the Process Identity.
}
This code is based on this MSDN article: http://msdn.microsoft.com/en-us/library/ms998351.aspx

Resources