How to get started with OAuth to secure a Web API application? - c#

I have a Web API application and I've understood OAuth would be the standard security model for APIs where an Authentication Server would become responsible to generate Authorization Tokens so that the user can send to our server and consume the services.
I'm very new to this but I understand the roles involved:
Resource Owner
Client
Resource Server
Authorization Server
But what is OAuth exactly in practice, not in theory? Is it a .NET library? Is it a service provided by a separate Company? Is it something I can configure on my local development machine and see how it works?
How to get started with OAuth to secure a Web API application?

OAuth is a protocol; the current version is OAuth 2.0. More to your question, that link lists several implementations of the protocol in various technologies. For use with the .NET Web API you're probably interested in DotNetOpenAuth which provides implementations of both OAuth 1 and OAuth 2.
I'm using DotNetOpenAuth in an app I'm working on now to secure a .NET Web API. I've got an OAuth2Handler which extends DelegatingHandler which is inserted into the Web API pipeline before incoming requests reach any controllers. OAuth2Handler does the following:
Instantiates a DotNetOpenAuth ResourceServer
Calls ResourceServer.GetPrincipal() which reads and decrypts an access
token (issued elsewhere by the AuthorizationServer and returns an
OAuthPrincipal (In my case I'm reading additional data that the DotNetOpenAuth implementation allows you to pass and creating a ClaimsPrincipal.)
Assigning the IPrincipal containing the user information read from the access token to the User property of the thread and current HTTP context so it is available from the ApiController.User property in the service controllers: httpContext.User = Thread.CurrentPrincipal = principal;
Honestly, getting this all working (e.g. setting up the authorization server, resource server, certificates, etc.) isn't trivial. Unfortunately there didn't seem to be a good guide on the DotNetOpenAuth site. Here's a few other tasks you'll have ahead of you if you go this route:
Implement IAuthorizationServer - This is the interface provided by
DotNetOpenAuth that allows you to plug in to the library and use
their implementation to issue OAuth2 access tokens. You'll also need to implement INonceStore and ICryptoKeyStore which I did using an EntityFramework context for storage.
Configure Certificates - The AuthorizationServer and ResourceServer each use certificates to encrypt/decrypt the access token ensuring they are only accessible to each other. I built some custom configuration so I could manage this configuration in the web.config files of my authorization server app and my Web API services (resource server).
Manage Refresh Token - When first requesting an access token from the authorization server you'll get back (depending on your configuration) both an OAuth2 refresh token and an access token. The services use the access token which should be short-lived. The refresh token is used to get more access tokens. The refresh token should be kept secret (whatever that means in your scenario). For me it means the refresh token is never exposed to client-side javascript in my web app.
I hope that helps give you a high level idea of how to get started with OAuth and .NET Web API. Here's a blog post demonstrating some of these steps. This SO answer gives a few more high level details of the client side of the picture.
(The DotNetOpenAuth online docs appear to be down right now... sorry for no links to them; Apparently it has happened before).

Related

Using JWT for authentication from WCF self hosted seever

We have a self hosted WCF REST API service (not ASP.Net). We currently support Basic and Negotiate authentication.
We would like to add support for JWT in a cookie, so that we dont have to authenticate against the DB on each call, and so we dont have to set headers. The main issue is that we want our web application, which uses the API to be able to provide links to retrieve resources for downloading without setting headers, ie rely on browser having a JWT pushed into a cookie.
We have an endpoint called /API/AuthToken, which supports Basic Authentication, but we’re not sure what the code to generate a JWT token, and pushing it to a cookie would look like. Specifically, what does the code for generating a JWT token should do.
I have not been able to find any documentation or samples on how to do this? Any leads or code snippets?

IdentityServer4 direct interactions via UI mobile app

I'm creating a centralized authentication system for multiple mobile applications. Its architecture is based on the OpenID Connect flow through the use of OAuth2.0 with IdentityServer4 on ASP.NET Core Identity.
I have researched a lot and in the main implementations with the Authorization Code Flow observed there is always the redirection of the user from the mobile app UI to the server web views, to allow the management of its profile.
This is very uncomfortable, because it significantly compromises the UX. I would like the user to be able to register and authenticate himself directly from the app interface without any redirection that involves opening a browser. Is there a way to do this with only API calls, from the client backend to the centralized authorization server?
You can use the Resource Owner Password Credentials grant type where you can pass the user credentials to the token endpoint and receive an access token. But usage of the ROPC grant type is highly discouraged as you can read in this blog post from Scott Brady, one of the creators of Identity Server.
What I can propose to you is to use Authorization Code flow to login the user and get access token for them, and then creating your custom API endpoints on identity server for user management. More on custom api endpoints here

Using IdentityServer4 as Class Library instead of Hosting Solution

I have been exploring IdentityServer4 for a couple of days. It performs hosting internally generating a connect/token endpoint which internally validates and generates an access token.
Even to call it a discovery URL is needed ultimately requiring a web app template for hosting.
Is it possible to use IdentityServer4 as a library that just allows access tokens to be generated?
**Updated Based on input from Bryan
What I am trying to achieve here is GSMA Compliance that requires both OpenID Connect and OAuth. I need to generate an Access Token as well as Identity_Token. But the caveat here is that IdentityServer4 hosts its internal endpoint where I do have custom endpoints. Also it require http based calling and I do require a sort of library that I can integrate and internally call to generate Access token as well as Identity Token.
** Some more update
We have hosted a custom GSMA compliant Web API Project and have hosted several endpoints as per required by GSMA ultimately validating and sanitizing the request landing on our endpoints. Internally we do require an Access token and Identity Token to be generated and shared back on the callback of the calling party. Currently, I have used an Identity Server template which is MVC based project ultimately requiring us to use at least two ports/project one for our Custom GSMA compliant APIs and one for Identity Server. Calling identity server via URL add a new hop and an HTTP request needs to be sent out to Identity Server whereas I was thinking to use IdentityServer as a class library somewhat allowing me to pass in input parameter and do get an access token/ identity toke.
Upon dissecting server Identity Server project like
Identity Server 4
Identity Mode
Identity Storage
I got the impression that it's very difficult to exact a library out of these projects that can help me generate access token/identity token easily.
IdentityServer4 is an OpenID Connect (and OAuth) identity service -- it's not just about tokens. Those technologies are primarily HTTP-based. Thus IS4 is built on top of ASP.Net Core's web tech. If you just need tokens (JWT, I assume), it's pretty simple to roll your own and use them however you see fit. A few Google searches (or an SO search) will provide you with the code needed to create your own JWTs (for example: https://houseofcat.io/tutorials/csharp/identity/createjwt). Without more information about how you want to use them, I can't elaborate on this answer.

User Login Authentication with Restful asp.net Web api and securing API

I am learning to develop asp.net Web API with AngularJS frontend framework. I have been doing a lot of research on this for about a week now.I have read about oauth 2, owin and other. But now confused which is better.
I have a couple of Question and hope you guys can help me with it.
1) In my application - Only Registered User will be able to have access in to application through log-in with email and password. Can someone please point me to a good resource or article on how to create a good registration and log-in authentication with API.Which is secure enough as i will be gathering user data and storing them.
2) What type of security i need to protect my API, at first the API would be behind the firewall and then ones project is finished it will be open to the world? and also please point me to right direction if possible.
Please note this is not a duplicate question i have been through most of the post on stackoverflow and asking this after i could not find answer.
Any suggestion or help on this is appreciated.
Thanks for all your effort on this topic
You can use token based authentication using Asp.Net Web API 2, OWIN, Asp.Net Identity and AngularJS.
Asp.Net Web API now fully supports OWIN. Katana is microsofts OWIN implementation.
Asp.Net Web API now supports authorization using OAuth 2.0. OAuth is made possible with Microsoft OWIN components.
Are yo confused with the terms Identity,OWIN,OAuth ... here is brief overview of them.
Asp.Net Identity is developed to overcome problems by asp.net membership system. Asp.Net Identity allows us to use different storages(Table storage,No SQL) and allows us to use external identity providers as it uses OWIN.
OWIN is to break tight coupling b/w Asp.Net and IIS. OWIN is just a specification. Katana is Microsoft's OWIN implementation. OWIN sits in http request pipeline. OWIN pipeline has middleware components, where we can mention external login mechanisms.
OAuth was created to remove the need for users to share their passwords with third-party applications.
Note:
Here Asp.Net Identity has nothing to do with OWIN, OAuth and vice versa. They are three separate concepts. Asp.Net Identity is Microsoft's implementation. OWIN, OAuth are open
standard concepts. Because Microsoft has implemented OWIN, OAuth is made possible.
So, Web API 2 uses OAuth bearer token instead of forms authentication cookie, which is more correct in Web API world. Because it allows to use variety of end user devices like mobile devices.
In your case, you can use the default templates provided in visual studio 2013.
1. Create New Project and select Asp.Net web application.
2. Select Web API or SPA template.
3. Change authentication and Select individual user accounts.
4. Click Ok.
Now, everything is configured by default in order to use OWIN, Asp.Net Identity, OAuth. Be cause we use token based authentication, you can find there is no login method available in Account Controller.
To register users, use Register method available in AccountController
To login, you need to post data in following format to
http://example.com/token (Which can be configured in StartUp.Auth.cs)
grant_type=password&username=Alice&password=password123
After login, we recieve bearer token, which we need to send with authorization header with every request to access protected resource.
As you are using awesome frontend framework AngularJs, you can save bearer token in local storage, and you can write a http interceptor service, which takes care of sending bearer token with each request.
Here registering the user is taken care by Asp.Net identity, where as authenticating user is taken care by OAuthAuthorizationServer which is present in Providers folder by default.
Bearer tokens, that we recieve are not towards a specific client,so any one can intercept them. So use them only over SSL.
Please go through this links
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
Vs2013 webapplication project template comes with a good owin setup. I suggest to look into that

using wif with web api

I got lots of articles and SO question based on Claim based authentication for WCF Restful Services, but I am using MVC Web API to develop RESTful Service (Not WCF Rest Service)...
So could you please help me to understand how to secure RESTful service using claim based authentication?
Here is what I need:
I have a Web App and MVC4 Web-API service
We have STS
The MVC Web App trusts the STS
Now the user logs into the Web App, he is redirected to the STS login page.
Once logged in, he is redirected back to the MVC Web Site.
This web app invokes the web-API Service.
Now, I have been stuck at point #4. We have a RESTful service, but need to implement WIF.
Can anyone please help me with this.
Note: I am NOT using WCF Restservice but using MVC Web API
From your description, it sounds like you are using a delegated identity model. That is, the user signs in to the web application and when the web application invokes the Web API service, it uses the identity of the currently logged in user.
If that is the case, then you need to configure WIF to save the "bootstrap tokens". The effect of this is that the original security token is available as a property on the current ClaimsIdentity. you can then use that to set the Authorize header of he request to the Web API service call.
To turn this on in .Net 4.5 you set the saveBootstrapContext attribute on the WIF element to true:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
...
For .Net 4, the config looks lke this:
<microsoft.identityModel>
<service saveBootstrapTokens="true">
...
Then to access it from the web application you do something like (depending on how many identities you have) this in the controller that is going to call the Web API. For .Net 4.5:
SecurityToken token = (User as ClaimsPrincipal).Identities[0].BootstrapContext;
For .Net 4:
SecurityToken token = (User as ClaimsPrincipal).Identities[0].BootstrapToken;
Having obtained the original security token, you can now attach it to the calls to the Web API as an Authorize header. Generally this will be attached as a Bearer token, which is just a fancy way of saying that you append the word "bearer" to the start of the header value. To attach the token, do something like this:
WebClient request = new WebClient();
request.Headers.Add("Authorization","bearer " + tokenAsString);
Note: Generally you will encrypt or base64 encode the token value in transit rather than attach the raw string, especially if it is XML, since some frameworks will mangle the XML in transit.
To convert the token to a string, you should user a class derived from SecurityTokenHandler There are a number of these included in the standard framework assemblies for handling some standard token types. For REST services, the JSON Web Token is a popular format and there is a NuGet package containing a handler for that here
https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/
If you are using some other token type, you can write your own handler (it is not difficult in fact) or try to find on on the web.
In .Net 4.5 the SecurityTokenHandler class has a WriteToken(SecurityToken) method that returns the token as a string. In earlier versions of WIF only the XML version of WriteToken was supported.
There are several samples showing how to use the SecurityTokenHandler for REST services on the server side. A good example is here
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc/view/Discussions#content
All the relevant code is contained in the global.asax.cs file.
If your client is not authenticated the your Web Api service should return a 401 Unauthorized response.
It will then be your clients responsibly to seek authentication and gain a new token. You should return the link to your log in form in the WWW-authenticate header
This video might help - Securing ASP.NET Web APIs http://vimeo.com/43603474

Categories