WebApi Authentication filter - asp.net-web-api

Please I need your help to understand this issue..
am building an Authorization server (ASP.Net WebApi hosted on IIS) which responsible for generating jwt tokens based on ASPNet Identity and a resource server which is ASP.Net WebApi OWIN self-Hosted on a Windows Service.
my understanding is the authorization filter executes "AuthenticateAsync", if the filter successfully validates the token, the filter creates an IPrincipal and attaches it to the request.
Please i need to know in the scenario described above
who is resposible for executing the AuthenticateAsync and loading the IPrincipal? and how does it work?

Related

How to secure a restful webapi core

I am working on a webapi core and have few methods within it. This is a restful web api.
I don't want a situation where people will grab my uri and start using it. I want only
authenticated users to have access to the webapi. I am new to this. I am using the webapi core.
A xamarin.forms app will be using this webapi.
I will appreciate some directions on how I can secure this.
I would suggest you below approach
User DB - either Identity or custom store
Authorize your web api controller
Use JWT for generating JSON web token and validating them.
Provide access if only JWT validates. Excellent support in ASP.NET Core API
Provide Login (token generator API endpoint), pass JWT for further API calls as Authorization header
I think this REST Security Cheat Sheet can be useful
https://www.owasp.org/index.php/REST_Security_Cheat_Sheet
https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/REST_Security_Cheat_Sheet.md

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

Transformation of token received from OpenID server

I currently have a distributed system containing an OpenID Connect server (IdentityServer3) acting as SSO server. The clients using the SSO server are AngularJS SPA:s with WebAPI v2 backends.
I got the basic login flow working, but I need some help with configuring the WebAPI/OWIN pipeline to allow transformation of the received token claims, ie. removing unnessecary claims and adding local claims. I'm assuming I need to create a local JWT instead of using the JWT received from the SSO server.
The question is, what is the best way of doing this? Are there OWIN middlewares that can help with this, or do I need to "manually" generate a new locally signed JWT from the claims received from the SSO server?
Current implementation details:
The AngularJS SPA authenticates against the SSO server using
authorization code flow and receives the authorization code.
The SPA posts the authorization code to the WebAPI.
WebAPI receives the authorization code and requests an AccessToken/JWT from the SSO server using the OAuth2Client class (part of Thinktecture.IdentityModel.Clients). This AccessToken is returned to the SPA to use in any further requests done to the WebAPI.
So my question mostly relates to step 3. How do I best change my current flow to generate a token also containing the local claims?
Also, what kind of authentication middleware should be used with your proposed solution (JwtBearerAuthentication, OpenIdConnectAuthentication or OAuthBearerAuthentication)?
Apoligizes for my probably confused terminology usage, I'm a beginner regarding OAuth and especially the OWIN pipeline. :)
Your WebApi should use BearerTokenAuthentication.
To get access token (access_token) and claims (id_token) in single call you need to set response type as ResponseType="token id_token"
You can checkout various ready to run sample at IdentityServer3 Samples. Specifically checkout implicit flow sample.

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.

Authorize using Oauth2 Token in Asp.Net WebAPI

Hello I am building an ASP.Net WebApi. First I authorized the WebApi using basic authentication .net membership provider and the Thinktecture Identitymodel.
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((username, password) => Membership.ValidateUser(username, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
I guess it couldn't be made any easier.
To take it a step further i've set up the Thinktecture IdentityServer which provides me with oauth2 tokens. My question is how do i validate the access tokens the client sends me (the WebApi) with the identity server?
I've been looking into the AddJsonWebToken methods the IdentityModel provides, but I can't really figure out wich uri (endpoint) in the identityserver i should call to validate the token. Probaply I'm just completly lost here and missing the point, any help would be greatly appriciated!
To summarize:
How do I validate the access_tokens i receive in my WebApi and how do I wire that to the [Authorize] attribute?
Simply call AddJsonWebToken in you web api config - and add the issuer name, signing key and realm uri.
There is no need to call idsrv for validation.
Here's a sample:
http://leastprivilege.com/2012/05/26/thinktecture-identitymodel-and-asp-net-web-api/

Resources