Using JWT for authentication from WCF self hosted seever - c#

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?

Related

How can receive an ADFS bearer token in C# without user log in

This is sorta driving me crazy. We got a Web API that takes a JWT bearer token received via ADFS. Now I have to write a Windows Service that communicates with the API but to do that, I need that JWT token.
I tried looking on the internet but none of the solutions work. Lots of examples use the WSTrustChannelFactory but none of them show how to specify a Client ID for the ADFS application or other relevant information.
Another example is MSAL.NET which supposedly supports ADFS. But all the examples and documentation are about Azure AD, but we have an on-premise AD. Some examples also point to example code that no longer exists on GitHub.
I managed to get a token with the ConfidentialClientApplication from MSAL.NET but it‘s not working, the API says it‘s invalid. And it seems it uses response_type code, rather than id_token which I need, and there apparently is no way to change that.
Other than these two, I can‘t find anything at all about this subject.
So: How can I receive an ADFS JWT bearer token with C# from a Windows Service application using the current user context, rather than requiring a manual username and password entry?
Any pointers would be greatly appreciated.

Asp.net core 3.1 securing API and web app

I have an ASP.net core solution that contains 2 projects and I want to add authentication for both of them:
I want the web app to use cookies-based authentication because it's easy to add.
But when I call an API from the ApiAuth project I want to be authenticated to use it.
WebAuth project contains the basic authentication (login, register...) but I can call ApiAuth project Apis without being authenticated. how can protect the ApiAuth project APIs?
I tried adding [Authorize] decorator but I am getting this error:
So I am thinking about adding a JWT authentication but I don't know if it's the correct thing to do or not?
Any suggestions, please?
If the API requests will come from the web app which was served with a cookie, and if the web and API share the same domain, you can use the same cookie for both. This is preferable to JWTs given that it also has the advantage of using secure, HTTP-only cookies which aren't susceptible to malicious JavaScript.
On the API, you'll add cookie authentication:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
Requests from the web app should carry the cookie as long as both use the same domain, like myapp.com/app and myapp.com/api.
This also requires both apps have the same Data Protection configuration, so they are both able to read the encrypted cookie with shared keys.

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

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).

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

Cross-Domain single sign-on with azure, ACS, Sharepoint 2010, MVC Site, and WebService

I have a SharePoint 2010 site configured to login with ACS. And ACS configured to use my own Identity provider. I also have a MVC web application which is also claims aware, and uses ACS for authentication.
The Idea is to expose certian services from sharepoint, to the MVC site, using the webservice I have build.
Here is a Drawing of the Idea:
My Idea was That once you log in to the MVC site you could use that SAML token(idenity) to log on to SharePoint(i just pass the SAML Token to the web service, and the service attempts to log in to SharePoint with that token). I was hoping since I configured The Relying Parties(MVC site, SharePoint) in ACS to use the same certificate for signing, it would accept the token even if it was from a different realm. But that isn't the case. So I was wondering how my web service could impersonate the user with the claims I have. I've been doing endless Research, and i'm pretty convinced this just isn't possible. The real question is, if there is a way for SharePoint to trust the tokens I get on my MVC site, without building an entire STS and having SharePoint have a trust relation ship with that. Any Help and ideas would be appreciated.
If you are trusting tokens that were created for MVC or SharePoint, then your webservice is part of that "realm" so it is ok to add that realm as a valid one. The audience uri validation can be changed from config or code. Are you using WCF? Are you using WIF with WCF?
<audienceUris>
<add value="your:sharepoint-and-mvc:realm" />
<add value="http://webservice" />
</audienceUris>
edit: reading your question again and the clarification you made, you will have issues with SharePoint, since they have an STS that will do some transformations to the original ACS token and sign it again with its own keys. Meaning that you don't have access to the original ACS token. I see two options here:
Create your own token before consuming the service (you can use SimpleWebTokens or JsonWebTokens which are more simple to implement and a shared symmetric key).
Configure your service to trust SAML tokens signed by ACS or SharePoint key as well the audience URIs.
Since this is a REST service I would go with option 1, transform the original token to a JSON web token, resign with your own key and attach the token to the Authorization header.
Here you have an implementation of JsonWebTokens (JWT)
http://nuget.org/packages/JWT
Here is an implementation of SimpleWebTokens
http://nuget.org/packages/netfx-Microsoft.IdentityModel.Swt
You can use JWT also with asymmetric crypto with x509 certs (it is not implemented in that package though)

Categories