I have an internal use web site that will be exposed over the Internet for ease of use on mobile devices. The web site is MVC 5 and will communicate with a Web API on a different server. The user will enter their Windows account information on the login page which will be authenticated against our Active Directory service. Once authenticated I would like to create an authentication token for use for subsequent calls to the MVC site as well as calls to the various other Web APIs.
At first we were just going to use Basic authentication since all channels of communication are over SSL however we have one Web API that will not have access to our AD but will have access to a central database that may contain token information.
Any examples or documentation about how to secure enterprise Web APIs would be fantastic. I can't find much information about this topic.
A way to do this would be to create a custom ActionFilterAttribute and override the OnActionExecuting method.
public class AuthenticateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//grab token from httprequest in the actionContext
//and authenticate it against the token in the database
if(/*token is NOT authenticated*/)
{
//set unauthorised response
var response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
//and set the httpresponse in the actionContext to the unauthorised response
actionContext.Response = response;
//then return
return;
}
}
}
You can then apply this attribute to any actions or methods in your api you wish to authenticate.
We ended up using thinktecture's IdentityServer.
https://github.com/thinktecture/Thinktecture.IdentityServer.v3
v3 Beta 1 was just released. Looks promising.
Support for OpenID Connect and OAuth2.0.
They have several client samples that you can download from a different repository.
https://github.com/thinktecture/Thinktecture.IdentityServer.v3.Samples/tree/master/source/Clients
Related
I'm creating a test project with our IDP server. We have created a simple Web API sample project which return the claims of the users on its get method. We have also created the token by using OAuth Flow GrantResourceOwnerCredentials or Flow 3 in specs. Few things i didn't quite understand, need some help to get some more understanding :-
How does the Web API knows that token is coming from authorized
client and how does it get validated.
Where in Web Api code, we can override and check the OAuth incoming token and its validation. In production environment, we will have separate HA server for IDP and Web API, so do we need to specify some certificate in web config?
Can we have all the Auth mechanism available to the Web Api? like basic , OAuth etc.
How does the Web API knows that token is coming from authorized client and how does it get validated.
Normally access token is passed through HTTP Headers like Authorization. You can use handlers in web api on specific routes and check this token with your logic
Where in Web Api code, we can override and check the OAuth incoming
token and its validation. In production environment, we will have
separate HA server for IDP and Web API, so do we need to specify some
certificate in web config?
As said above. Best place is handler
public class AuthenticationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//...
}
}
and don't forget to configure to use your authentication handler for some specific routes
public static void Register(HttpConfiguration config)
{
// ...
config.MessageHandlers.Add(new AuthenticationHandler());
// ...
}
You need certificate only if your logic needs this certificate to validate your token. The best way is to store and read it to/from windows certificate storage and configure in web.config only thumbprint of certificate you need, so no user names, or plain text password in web.config.
Can we have all the Auth mechanism available to the Web Api? like
basic , OAuth etc.
Yes, you can use basic authentcation together with OAuth, just use something to differentiate, like different HTTP Headers suitable for autorization, but it's not clear for me, why you need to support e.g. basic together with oauth, maybe it will have more sense to use only easier one - basic.
Most of information you need is gathered here http://www.asp.net/web-api/overview/security
I have an Asp.Net Web Api 2.0 based web services which provides functionality such as customer login and access to their information after login. I am using Bearer token authentication for customer login.
Now, lets say I want to restrict access to my web services to only some specific third party vendors who build mobile applications. What are some of the patterns to achieve such restriction?
Its all built in already in the aspnet membership db.. User and roles table are already there.... you just gotta fill them and use authorize tag.. you did not search on google right?
// Restricted by user
Authorize(Users="smith")]
public class ValuesController : ApiController
{
}
// Restricted by Role
[Authorize(Roles="admin")]
public class ValuesController : ApiController
{
}
http://www.c-sharpcorner.com/UploadFile/2b481f/Asp-Net-web-api-authorization-and-authontication/
I am working on Asp.net MVC5 app and a Web APi2 ,The API is to be used across multiple sites and to be used to authenticate the user as well.
I have created the MVC5 and Web API project in VS 2013,The default template for the authorization server comes whith grant_type=password,but I am looking for implemantation using Code authorization flow.
I have created the Login view in my WebAPI+MVC project which should be called by the client application
I should validate the user using username and password
If user is valid then pass the Authorize code to the client application using redirect Uri
I am getting confused in integrating above flow using owin "OAuthAuthorizationServer"
or what exactly I should override in below method
public override Task GrantAuthorizationCode(OAuthGrantAuthorizationCodeContext context)
{
return base.GrantAuthorizationCode(context);
}
I will be thankful if any one can guide me with the implementation.
I'm having hard time in deciding an approach while implementing Authentication/Authorization scenario for my Web API (Service) - MVC (client) architecture project. Even though i have implemented Custom token based authentication in Web API project, I'm finding it hard where exactly i should implement the authorization (In Client or in API itself).
Architecture Overview :
Projects Solution -
|
| __ ASP.NET Web API based REST service (Independently hosted on IIS at M/C 1)
|
| __ ASP.NET MVC based Client (independently hosted on IIS at M/C 2 Consuming REST service)
|
| __ Smart phone client Application (Consuming the REST service)
Already implemented authentication :
Token based authentication in Web API (using Message Handler) - Which generates SHA1 encripted token for authenticated user which needs to be a part of every http request header for authentication.
(Token = User Name + User IP)
SSL protected HTTP request. (Again, Using Message Handler)
Current problems :
At what layer the authorization should be implemented?
How does user role should be persisted at client? Using Cookies? or Adding role information to Token itself ( Which might add overhead for API to decrypt the information and extra DB calls to retrieve permissions associated with that role)
How the Authentication Token should be persisted with Client session?
Since, my application is SPA MVC application, What is the best way to include the Authentication token as a part of every AJAX call i make to API?
I hope, I'm not doing things wrong while taking the whole authentication/authorization concept in to consideration. Thus, I'll appreciate any alternate approach/suggestion.
First of all I think it's never a good idea to invent your own authentication mechanism.
To answer your current problems:
1 Generally spoken you always want to secure your Api using authentication since it's the place where you access your data. Your client (MVC App/Smartphone) should authorize itself to get access to your Api.
2 & 3
Since you are using a REST Api I would suggest to keep your Api stateless, with other words, don't keep any session information. Just include the role data you need in your Token. You could use for example an JSON Web Token.
4
I would always use the authorization header to send authorization data. In your DelegatingHandler (Note the difference MessageHandler MVC, DelegatingHander HTTP) you can simpy retrieve the header.
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var authorizationHeader = request.Headers.Authorization;
// Your authorization logic.
return base.SendAsync(request, cancellationToken);
}
For more info on how to include the authorization header in an ajax call please see: How to use Basic Auth with jQuery and AJAX?
Extra info:
If I were you I would also take a look at Thinktecture's Identity Server: https://github.com/thinktecture/Thinktecture.IdentityServer.v2
And maybe this answer about REST Service Authentication will help you as well:
REST service authentication
Why create an entire token system (unless you're using some kind of federated security) you have forms authentication and cookies, once the cookie is set and returned the browser will send the cookie with any AJAX requests made by your SPA.
I have found a lot of material on the web about using the ASP.NET Membership Provider with the wsHttpBindings, but I haven't seen any reference to using it with webHttpBindings.
I am looking for a system that will work in two scenarios:
The user is logged into an asp.net website and the website is making calls to the service.
The user accesses the service directly via REST.
Is this possible using the built in framework (i.e. just through configuration)? If so how do I configure the service? And how does the user pass the credentials to the REST service?
The best source I've found is here: http://www.leastprivilege.com/FinallyUsernamesOverTransportAuthenticationInWCF.aspx
The site also has tons of other information about setting up HTTP Modules to handle basic authentication (which I'm guessing you'll be using since it is kind of the standard).
The HTTP Module authentication method is located on Codeplex with sample code and everything here: http://www.codeplex.com/CustomBasicAuth
ADO.NET Data Services you mean?
You can build a QueryInterceptor for an entity and limit the access to it.
For example:
[QueryInterceptor("foo_entity")]
public Expression<Func<foo_entity, bool>> FilterMembership()
{
MembershipUser user = Membership.GetUser();
Guid userGuid = (Guid)user.ProviderUserKey;
return c => c.UserId == userGuid;
}