Repeating logic in each ASP.NET Web API request, where should that go? - asp.net-web-api

I need to store some information in session(or in whatever in ASP.NET Web API) that I need to retrieve in each API request. We will have one api IIS web site and multiple web site binding will be added through host header. When any request comes in for example, api.xyz.com, host header will be checked and store that website information in session that will be used in each subsequent api request when making a call to database. Hope this is clear.
I found a way to handle session in ASP.NET Web API. ASP.NET Web API session or something?.
I know lot more about asp.net web forms where we can override PreRequestHandler. I am looking for similar in ASP.NET Web API where I can have my logic to get database id for api domain(for example, api.xyz.com) and store it in session which I want to access in each API GET/POST request.
Somebody will definitely say by adding session I am making it stateful but REST is stateless. But I wanted to save database trip for each api request. If I don't use session or something similar, I end up repeating the same logic for each api request.
Is there a better way to handle this situation? how?
thanks.

If that logic needs to happen for all requests, you better use an Implementation of delegating handlers.

Related

asp.net Web Api saving user information in session context

I'm trying to create an asp.net web api that calls an external api and gets a response that needs to be stored server side in session context and then later reused in further calls.
What will be best practice for this?

AJAX calls within MVC and Identity Server

I have been playing with Thinktecture IdentityServer3 and am keen to use it as the product looks great. However, I don't fully understand how to accomplish my flow which is probably fairly common:
Create Identity Server using Implicit flow
Setup an MVC web site
Setup a separate Web API
So far so good, as demonstrated in the examples on the site. I now wish to call the API using AJAX calls directly but for this i need an access token. It seems like a large overhead to have to route these through the MVC site itself (again, in the examples).
How can I accomplish this flow? Would it essentially blend the MVC and Javascript Client samples or is there a smoother way so the user only has to sign in once? Perhaps send the access token in a hidden field but then how would it renew?
Any help on understanding this would be great.
I've managed to come up with a solution which seems to work, not sure if it's best practice though...
Expose a method on the MVC site at AJAX/AccessToken
Method should be locked down with Authorize attribute to ensure the MVC part of the site is authenticating properly with IdentityServer
Method returns the users Access Token which was generated through the above call via MVC controllers
In JavaScript, simply use this endpoint to get an Access Token and then call the API manually
The call to get the Access Token should be secure as its within the same domain/authentication model as the MVC site itself
I've put up a sample here for anyone interested:
OIDC-Website
Check out the form post client to see the endpoints being called explicitly. You will need to hit the token endpoint to get your access token.
You should be able to use these endpoints in your AJAX calls, store the received claims and tokens in a cookie and take it from there.
Note that to renew the access token, you will also need to store the refresh token. The Implicit flow does not allow for refresh tokens (you'll need to use the Authorization Code Flow or the Hybrid Flow).

Simple Web Token (SWT) Authentication in Web Api 2 OData endpoint

Ok, the situation is this.
We already have an existing ASP.NET MVC 5 site with Custom Forms Authentication, Logon, Registration etc with a custom database for roles and profiles already implemented.
We now are adding some new functionality to the MVC site and we decided to use Web Api 2 OData 3 endpoint which lives in another domain. The Web Api currently doesn't include any authentication but we need to be able to map the requests to a certain user to get his roles etc from the backend. The MVC and API sites use the same backend.
What we would like to accomplish is, that when the user logs on in the MVC site, the MVC site calls the Web Api server-to-server with the user's credentials and receives a token that the client can then use to call the web service with.
When API receives a request with the token, it can then map the request with the user in backend and do authorization.
As far as I understand it, Simple Web Token (SWT) could pull it through. But considering the environment, .NET 4.5.1 / Web Api 2 / OData 3 with Entity Framework in Azure Web Role, I started thinking is this SWT something I should really use or if there is any NEW technologies recently published that could easily pull this through. I don't want to add any unnecessary 3rd party dependencies to the project if the .NET stack already contains something like it.
So, what would be the simplest way of pulling this kind of authentication through without adding unnecessary dependencier to the project.
The solution we are looking for, is only temporary meanwhile we redesign our authentication scheme. So we are looking for something really simple to implement that works with least dependencies that need to be removed later on.
I'm using this in a project I'm currently working on. I use the OAuth 2.0 OWIN Middleware component that ships with Web API 2.0 (if you add a new Web API project with Authentication enabled, it includes the base infrastructure).
You would use the Resource Owner Password Flow as defined in the OAuth 2.0 specification. Basically you request a Token from the Web API OWIN Middleware sending:
client_id - identifies your MVC endpoint
client_secret - identifier your MVC endpoint
username
password
And in response you get a bearer token. The token generating is based upon a claims principal, the OAuth middleware component has predefined hooks for adding claims. This token now needs to be added as authorisation header to each response. On the MVC side you might add this to session so that it's always available to make backend API calls in the context of the user associated with an incoming HTTP request. If you're using WCF Data Services Client, you'll need an authorisation service/manager or similar that you can hook into OnRequestSending and OnResponseReceived events, so that you can insert that bearer token into the HTTP headers.
You can customise the OAuth Middleware component as you need to quite easily, it took a bit of time to figure it out as it's not too well documented, but downloading the Katana source code did help a bit as the source code does have some good documentation.
The nice thing about it all is that you simply need to enable HostAuthenticationFilter and add Authorize attributes on the Web API side and it's ready to go. You can get access to the claims principal object and use claims as identifying pieces of information for your user - e.g. identity, roles, other attributes etc.
To get started, look at http://www.asp.net/vnext/overview/authentication/individual-accounts-in-aspnet-web-api
Also as a wrap, I did consider the use of JSON Web Tokens (JWTs) as there is an OWIN library available for generating and parsing these. The use case here would be that you authenticate, get a JWT back, and then use the JWT to get an OAuth 2.0 bearer token. The JWT is useful if you want to move authentication elsewhere, or if you want to get additional information about the user at the MVC side of things.

Better Architecture: Oauth with JQuery Ajax or JSP for secuing Servlet?

In a previous post, I had asked the SO community what may be the best way of securing my Servlets so that a user could not simply rip out my url from src and use it as a free api of sorts:
How to keep Servlets to my site only (some sort of authentication)?
I was directed to look at OAuth 1.0 as it is stable and well supported.
Thinking more on it, what if I used JSP in place of OAuth and jquery ajax?
I could still put all main hard coded files on my Varnish servers and just the ones that need dynamic content would be JSP files that called Servlets for their data, thus not exposing any Servlet address.
Question(s): Would this JSP model be acceptable in a production environment? Or is best case scenario to stay with jquery ajax and oauth? Is the difference in speed considerable between these two different scenarios?
In the previous question. I don't know that OAuth is strictly the answer (though it could possibly be used). OAuth is really more geared towards allowing usage of your services via third-party authentication and authorization. In your case, I don't know who that third party would be.
What it does sound like you might want is the concept of an authentication token. So before a client can call your services, they would need to call one of your services to get an authentication token. All requests against you servlets would then need to also pass this authentication token and have the token validated as being active prior to you issuing a response.
You mentioned that your servlets are stateless (which is certainly appropriate for many API's), but I am wondering if the client application as a whole has state such that it could acquire such a token via some event (client application login for example) and be able to store the token for sending with each request against the servlets, as well as be able to handle refreshed tokens as tokens near their expiry.

Securing jQuery calls to Spring MVC REST API using Spring Security

I'm developing a REST JSON API with the Spring MVC Framework. I want to serve a single HTML application to the user and the whole communication between server and client is done with JSON format. So the client single HTML application uses jQuery to send AJAX calls to the server.
My big problem is to find the right way to do integrate a proper security technique. I read a lot about basic, digest or form based authentication via Spring Security, but I don't think this is the right way. I want to get JSON responses if the user isn't logged in and I don't want to send a jsessionid with each request.
Could you please tell me the right way or the best-practice how to authenticate user by performing AJAX requests? Maybe it's OAuth 2-legged? (don't have much clue of OAuth)
If you don't want to store auth information in server-side session (and use JSESSIONID in cookies/urls) you may send auth info with every ajax request using BASIC auth header (created in JS).
I've never used 2-legged oauth, so I won't comment about it.
edit: typo

Resources