Passing Authentication between MVC Application and WCF Service using Identity 2.0 - c#

I have created a WCF Service that runs in IIS and is published in a website.
I also have a MVC application that uses indentity 2.0 to authenticate and authorize my users and this application is connected to a SQL Server database with user information. This applications consumes the WCF service.
What I want to know is if it is possible to use the user credentials from authenticated user in the MVC application to make calls to the WCF Service and, if yes, which is the best practice for doing this.

I've finally found an answer for this subject.
When calling the web services from your asp.net mvc app you can pass the cookie like this:
var request = HttpContext.Current.Request;
var cookie = request.Cookies.Get("IdentityCookie");
var ticket = cookie.Value;
Pay attention that in this line var cookie = request.Cookies.Get("IdentityCookie") It will not work in your case because I renamed the cookie, if you didn't rename the cookie you replace "IdentityCookie" for ".AspNet.ApplicationCookie" otherwise just replace it for your cookie name.
(In my case I have a class that auto sends message headers in every request, the cookie goes in that header, you can make something similar)
Then you just need to make a message Inspector in WCF side so that every request pass to that inspector before calling the service. In that Inspector you can decrypt the cookie and check if the user is authenticated.
It resolved the problem for me, I hope this can help.

Related

Handling authentication/authorization: ASP.NET Core Web Application => ASP.NET Core Web API => SQL

I'm currently trying to work out the best way to handle authentication for a new external web application and web service application using ASP.NET Core. Here is the general setup:
Username/password is stored in SQL Server database
Web application ONLY makes call to web service
Web service (Web API) makes calls to database and returns data to web application
So the idea is that the user logs in once and using the built-in cookies authentication provider will stay logged in. However, I want to pass that authentication token or whatever to the web service application and have whatever it does run under the appropriate security context for that user. I've looked for examples that resemble this design but haven't found a good one. Could anyone make any high-level recommendations or point me to some helpful resources on how I can achieve this design?
Take asp.net core MVC and web api as an example, put the login page in the web application. Put cookie authentication in web api. After the user logs in, it applies for a token through the web api, and the token will be stored in the cookie cache of the browser.
Here is the cookie configuration. In Startup.cs (web api).
services.AddAuthentication("scheme")
.AddCookie("scheme", options =>
{
options.Cookie.Name = "authname";
});
If the token is successfully applied, it will be written in browser.
Then I add a action that gets the cookie tocken.
[Route("getTocken")]
public string getTocken( )
{
string cookie ="";
HttpContext.Request.Cookies.TryGetValue("authname", out
cookie);
return cookie;
}
This is the result.
This cookie tocken could be saved in session for maintaining state.

how to authenticate user with rest service-wcf WebHttpBindig?

I have a server-client project written in c#.
I want to change the client side to a web client so we can open it with the browser. So I decided to make a WCF rest service that will replace the server side. The binding that I am using for the service is webHttpBinding.
My problem is with the behavior of the service. The service data (vars etc..) is initialize after every call. If i add the [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
it doesn't change anything. If I use [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)], it works but I guess that the service instance will be the same for every client.
I have a simple html web page that get a username and password from the client and post it to the service. The service check the Login info with the user database and response. My problem is that i can't save the user status as logged in or not because after every post/get method the service is reset.
what should I do?
This is a pretty standard issue you have to deal with when trying to maintain a session over HTTP, which is what webHttpBinding is using. Even if you try to force it to have a session, it won't. RESTful services don't work that way.
A high level overview of what you have to do is have the service create a token it gives the client upon initial authentication (probably to be stored in a cookie), which the client will then send back with each request. The service can then use that token to check if the client is logged into a particular account with each request. You probably want to make tokens expire after a certain duration (might be 1 month, 1 week, 1 day, 10 minutes, depending on your application).
You can find some more information here:
RESTful Authentication
SPA best practices for authentication and session management
Authentication, Authorization and Session Management in Traditional Web Apps and APIs

Authorization with OAuth Bearer Token provided by External Web API

I'm posting this in the hope of receiving some feedback/advice and information on something I've been struggling with the last few days. To start I'll give a quick breakdown of the project.
There are 2 applications in the solution:
WebAPI resource & authorization server - Uses OWIN (hosted in IIS) and ASP.NET Identity to issue an authentication token on a correct login and then allow requests to the various controllers.
MVC client application - Has no authorization as of yet (until I figure it out) but will make calls to the WebAPI resource server to get all data. These calls will only ever be made from actions of the controllers in the client app, no client side AJAX calls.
The client application doesn't have it's own datasource. All information is stored in a database which the WebAPI service has access to, so essentially if they provide the correct credentials and the client app receives a bearer token I need to deliver a way for the application to see them as authorized.
What's the best way to handle this?
Is it possible to configure OWIN on the client side to use the OAuth
settings of the server? Am I barking up the wrong tree and will I need to just use HTTPClients?
Could I deserialize the bearer token and store it in session, and
then write my own authorization providers to check these on the client side?
My initial concerns are I'm abusing Bearer Tokens and trying to cobble them into a solution which isn't ideal. All examples of external authorization I've found so far usually involve making calls to providers hosted by Google/Facebook/Twitter to check the user is who they say they are, and then moves on to creating a user record in their system. My application can't do this.
In regards to security I was planning to introduce filters which would validate the request has came from the client application by providing an identifier and secret, along with IP validation.
I realize this may be a bit open ended, but I'd appreciate any advice. The scope of the project is that the web service is the only thing to have access to the database. The MVC client application will be hosted on a different server, and the service will only accept requests from said client application.
You don't need to access the data source in your MVC app to validate the bearer token. Basically, you can do it in the following way,
MVC app requests access_token from webapi and passes it to the UI client (let's say a browser).
Browser stores the access_token in a cookie/localstorage and sends them to the MVC app for all subsequent requests.
Create an ActionFilter in the MVC app to validate if the request from the browser has the token supplied in the header. If not, reject the request.
MVC app passes the access_token in the Authorization header to the webapi.
Use HTTPS for all communications (between MVC app <-> Client and MVC app <-> WebAPI)
You can further obfuscate or encrypt the access_token you get from the WebAPI on the MVC app side for additional security but then you will have to send the decrypted version back to the WebAPI.
I realize that my answer is a bit late, but maybe it helps other people:
The bearer token that you get from the API has a list of claims encrypted that only the API can decrypt. I assume you need to have these claims on the MVC application as well so you can restrict resources on the client.
So, what I have done was to first get token. After you get it, you make another request to the API resource api/me/claims to get the list of readable claims on the client. Based on this list you can allow access to resources in your MVC CLient Application using a custom claims based Authorize attribute. Also, you can store the claims in a cookie in the client session. Below is the code for the API controller to get the Claims.
[RoutePrefix("api/me/claims")]
public class ClaimsController : BaseApiController
{
[Authorize]
[Route("")]
public IHttpActionResult GetClaims()
{
var identity = User.Identity as ClaimsIdentity;
var claims = from c in identity.Claims
select new
{
subject = c.Subject.Name,
type = c.Type,
value = c.Value
};
return Ok(claims);
}
}
The idea is to reconstruct the ClaimsIdentity object of the logged User on the Client side and maybe add it to the session.
The token is not enough. You might risk getting a Not Authorized response from the API on a resource that you have made visible for the user in the MVC Client Application. Needles to say that is recommended to use HTTPS for all requests.

Authenticate MVC client against self-hosted Web API (OWIN/Katana)

I have a Windows Service running a Web API hosted as a OWIN middleware - the server. The API uses application cookie authentication and validates users against a database, using OWINs identity model. Now I would like to authenticate a user who accesses the API through a standard MVC web application (the client), but I'm unsure how to achieve this, e.g. after I received a response along with the cookie from the API, where do I have to store it inside the MVC application so that the cookie will be automatically sent along with further API calls.
You won't need to. Cookies are stored by the client's browser, and are sent to the web server with every request on the same domain name. Each subdomain will have its own sandbox for cookies. The main domain's cookies can be accessed by all subdomains.
MVC application will store it in the users browser the cookie. If you need to find an alternate way to achieve it, why not try localstorage. You can then send the authorization token with every request header using your Ajax calls. If you are interested in an Angular Application, here is an excellent tutorial that should help clarify a lot of question.

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