How to authenticate user while calling WCF service using AJAX? - ajax

I have a WCF service which needs to be called from client side(ajax call).
I want to use ScriptManager on ASPX page to add a ServiceReference to the WCF service (or) JQuery ajax call to the WCF service. I want to deny anonymous users accessing the WCF service. Is there any way to do user authentication before calling a service method from JavaScript? how to secure my WCF service calls from client side?

There are a number of things you can do to secure your WCF services. Probably the easiest way is if your services are already part of the existing overall ASP.NET application is to enable ASP.NET Compatibility Mode for your services. If your ASP.NET app uses authentication to validate users (e.g. forms authentication) and you are enabling that via a session cookie, then ASP.NET Compatibility Mode does most of that work for you.
By default, this is disabled, but you can enable it with an addition to your web.config:
<system.serviceModel>
...
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
...
</system.serviceModel>
This will enable compatibility mode for all your services in your application. You can also enable this on a service by service basis by setting the web.config value and also using the AspNetCompatibilityRequirements attribute on your service class not the interface):
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class FooService: IFooService {
}
When you enable this setting, you have access to HttpContext.Current (like an ASP.NET page) and it will also enforce that a user must be authenticated before accessing the .svc file (just like you have to be authenticated before accessing any .aspx file). If you try to access a .svc file without being authenticated, and you're using forms authentication, the caller will be redirected to the default login page and, after successful authentication, will be redirected to the .svc file.
This suggestion makes a few assumptions:
your services are in an ASP.NET application;
you're using some type of ASP.NET authentication (like forms authentication) to validate users' credentials and persist a validation ticket in a cookie;
This suggestion, while maybe not the most secure or robust, is probably the simplest to at least get up and running and secure your site to a reasonable degree.
Here's a good MSDN library intro article on ASP.NET compatibility mode.
If this works, perhaps the next step is to look into something like HMAC authentication (which involves a bit more work and the coordination of secret keys - but it's definitely more secure IMHO). Here's a nice walk-through of implementing it - http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/22/how-to-implement-hmac-authentication-on-a-restful-wcf-service.aspx
I hope this helps. Good luck!!

I'm not sure if this will help but I placed a layer between my WCF and webapp. I'd make an AJAX servicereference call to a local asmx. This came under the protection of the forms authentication ticket. The asmx would then do any further security checks (if that specific user making the call was allowed to request that data or shape the data based on the user) and then forward the call on to my WCF service.
This way my service layer did not need to know about the users for each app accessing it and only had a concern for delivery of requested data.
The asmx webservice took the responsibility of security.
Then I made the WCF hosted in IIS using WAS and only allowed Windows Auth access for the identity that the webapp app pool was running as.
So:
ASPX -> ASMX WebService -> WCF
I think that would give you the control/separation and security you are asking for?

for WCF web http service The only way to secure a Web endpoint is to expose it through HTTPS, using transport security. When using message-based security, security information is usually placed in SOAP headers and because the messages sent to non-SOAP endpoints contain no SOAP envelope, there is nowhere to place the security information and you must rely on transport security.

Related

Authenticate MVC clients with Web API Tokens

Currently I have created a WebAPI Project using identity framework and I have setup tokens to be returned when authenticating with the API.
So now I am looking at creating a standalone MVC application that will allow the user to make calls to the WebAPI to get back end data.
The goal is to separate functionality so that other applications can also start interacting with back end data through web calls.
So the confusion now is how do I setup my MVC project so that I can use the Authorize attributes on controllers with the token received from the WebAPI. I think I need to enable bearer tokens in the ConfigureAuth method in Startup.Auth.cs. However will that be sufficient enough? Or do I also need to enable the cookie authentication?
MVC and Web Api are fundamentally different when it comes to authentication. With Web Api, the bearer token has to be set in the header of the request, but this is not an issue as all API requests are done programmatically by the client, i.e. there's human-intervention involved in setting up the client to authenticate the request properly.
MVC is a different beast in that the actions are accessed generally via a web browser, which will not automatically affix a bearer token to the request header. What it will do is pass cookies set by the server back to the server. That's why cookie auth is used most typically for MVC web applications.
What you should do is enable cookie auth for the MVC site and then set up your sign in action to authenticate via the Web Api. When you get back a valid auth from the Web Api, then you can manually sign in the user via the Identity API:
await SignInManager.SignInAsync(user);

Recommended way to secure ASP.NET 5 Web API application

In previous versions of ASP.NET you got authorization and authentication out of the box from the default template.
I have a Web API application and three or four well defined clients that will consume it and I need to secure it.
I read about OpenID and OAuth but they seem like an overkill for my problem.
What's the simplest way to achieve that?
These would be the 3 best solutions if you require security:
WEB API browser client: Implicit OAuth 2 flow
WEB API Application client: OAuth2 code flow
(With OpenId)
OR: Cookie Authentication with Cross-site request forgery protection. (Default template MVC 6 website template)
If your application is public, I would use at least one of these, otherwise it depends on how secure your data must be.
Well, it depends on your scenario. If you don't need authentication (because it's a server-to-server scenario), use a security token as described below. If you need authentication of the user, you may use Basic or Digest security combined with HTTPS.
In a security token scenario, the client simply has to add the token to the request headers and the server needs to validate the token. Make sure the requests transit as HTTPS to make sure the token is encrypted. Remember, this method is only valid if you know the applications that will access your API will be in a secure environment (another server, for example). Otherwise, I would go for another solution.

Spring authentication through REST Service

I have a Webapp that consists of a REST API, and then another app that represents a frontend of this API. Both of this apps are developed using Spring.
Currently my REST api is not secured and data can be accessed directly by calling the REST endpoint without additional security info.
My frontend does have a login form (I'm using Spring Security for that), but does not have access to a database (the only access is through the REST endpoint). So the login process is done through an extension of the AuthenticationProvider that calls the REST api with the user and password and then responds with the authentication result. No authentication/authorization is kept on the REST side since to my knowledge this protocol should be stateless.
The problem is I need to incorporate ACL into my app, so that a user can only see those resources he's authorized to see (i.e. those he created). But given that my authentication process takes place on the frontend layer (which is where I keep a session attribute with the user info), I have two main problems:
How can I secure my REST channel?
How can I know which user is making the request on every communication, without explicitly passing the userdetails in each API request? is this even possible?
Doing it stateless and making two separate web application usually is overkill.
What I usually end up doing is.
Make my RestAPI stateful, because usually scaling is not an issue and simple form authentication will suffice.
Combine a Rest API/HTML Client in one Webapplication. If you want to keep it modular, you could create a Rest API module and integrate it as a JAR file in the lib folder of your web app.
Here is also some thread which goes through different alternatives for a rest API.
How to do authentication with a REST API right? (Browser + Native clients)

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.

How to design authentication and authorization system for REST backend / Ajax front End Application

I am starting a new project where we are planing to build a restful back end and an AJAX font end. I am approaching the problem by focusing on Identifying all the resources that I have and what the various HTTP verbs will do them, their URI and the JSON representations of those resources.
I am looking for the best design for securing the backend. Here is the list of designs I have considered. I am looking for alternative designs not listed below, and pros, cons recommendations. The system will be implemented with Spring 3.0 and possibly Spring Security 3.0, SSL will be used for many parts of the system but not for all of them, so some requests may come on SSL and some might not.
Option 1: Use the HTTP session
Show a standard login screen, create a server side session and let tomcat send back a jsessionid cookie and have the ajax client include the JSESSIONID cookie on every XHR request. This options just feels like it's the wrong approach for the following reasons.
The connection becomes statefull which is against the rules of REST
I want to be able to split the bakcend into multiple seperate WAR files which means i could have multiple HTTP sessions on the backend, if that is the case then this approach does not work. While I don't need the ability to split the backend into multiple apps today, I would prefer a design that allows for that possibility.
Option 2: Find an open source Java based security library that does this
Other than Spring security I have not found any other Java libraries, any recommendations are highly appreciated.
Option 3: Try to use an existing protocol like OAuth
In my very brief look at OAuth it seems that it is designed for authentication across sites where each site has it's own user database. In this system i want a global user database shared across all the backend ajax services.
Option 4: Use SAML and Shiboleth
This options seems over kill and hugely complex to setup and maintain.
Option 5: Send the username and password with every request
This requires that user sends their username and password with every request, which means that the front end AJAX app must store the username and password as a JavaScript object and if the user navigates away from the page then back the username/password combo will be gone and the user might be forced to log in again. I don't want the front end to try and put the username and password into cookie as that would comprise security.
Option 6: Implement my own authentication / Authorization protocol
Create a REST service that users can present their username/password combination to and then get back and security token, which they must send back to the service with every request. The security token would be digitally signed by the service and would have an expiry time. The token would be only good for most operations high security operations would require a new login screen as port of confirming the operation.
Problem with this approach is I have to invent yet another security protocol which seems like a total waste of time.
I am sure I am not the only person up against this problem, I hope the stack overflow community can point to some options and tools that I have not found yet.
Take a look at Apache Shiro. It is an authentication system that has a session management feature that can be used to share sessions across applications. This may be the easiest thing to do.
Or you could use Spring Security (or Shiro) with a Remember Me cookie that is shared across the webapps (as long as they are in the same HTTP domain). The remember me cookie would be analogous to your token in option 6. You can set the expiration on the cookie that so it is short lived like a session cookie or long lived like a regular remember me.
You might also want to take a look at Jasig CAS - Single Sign-On for the Web. It has a REST API and a protocol (Proxy Tickets) that allows services to proxy user AuthN to backend services like you described in option 6. http://www.jasig.org/cas
Briefly...the application that serves up the AJAX client is protected with Spring Security (supports CAS out of the box) and gets a Proxy Granting Ticket that you embed in the AJAX client. The AJAX client uses the PGT to get Proxy Tickets for your REST services...protected with Spring Security too. The REST services get an authenticated userId without every touching primary credentials.
Alternative, you could keep the PGT on the server and use AJAX calls to retrieve Proxy Tickets that are then used by the AJAX client to call you REST services.
As I understood you are going to secure a rest application, to preface you must know that a security provider consisd of three concepts (3A):
-Authentication
-Authorization
-Auditing
to implement these three together you must provide bunch of tools such as :
-SSO provider
-Session Store
-Open Id pattern
-user credentials integration
....
I have used ACL(Spring ACL) to provide authorization services and oauth2 for authentication.
there is one channel to connect these two together and its scopes(oauth2 scopes) but the problem is scopes are not flexible(pure strings) enough to implement authorization modules such as role_voter, cache_strategy, black_list or,Role_base strategy, exceptional permissions, white_list... (but you can use #EnableGlobalMethodSecurity)
In my case I used authorization server as a resource for oauth2 authentication server(take a look at http://projects.spring.io/spring-security-oauth/docs/oauth2.html), then I considered two spots to check authorization, the first I issued ACL to front-end and forced programmer to design her page dynamically up to ACL concept, the second is in back-end on service layer(BLL) using Aspect when one rest is going to be called. I sent the service key as an actee to check if current user has enough access control to do that. and for auditing you must monitor all requests I mean you must use an listener in your gateway or broker...

Resources