Authentication and Authorization in asp.net core WEB API - asp.net-core

I am new in asp.net core and want to implement authentication and authorization in WEB API 2 project. I am little bit confuse to use basic authentication, bearer token, JWT token or any other. please suggest more preferable
Thanks

Basic auth is as the name suggests, very basic and not very secure, it uses base64 encoding of the username and password so you must use HTTPS if you use it, but best is not to use it at all.
A bearer token is a type of token which effectively gives access to a resource to the "bearer" of the token. Both basic and bearer are used in an HTTP Authorization header.
You can have different formats of bearer tokens, one of which is JWT - JWT is the industry standard so I recommend you use it, and therefore you'll be using bearer tokens.
This article is a good starting point to look into all this in the context of asp.net core. See also this video series and this article goes into more detail about JWT validation.
Edit
To answer your questions in the comments:
OAuth is a standard for users to delegate permissions to apps or websites to access their resources, for example when you allow some web app to post on your behalf to your Facebook feed. Various tokens are used in this process and they're very often JWT. OAuth2 adds authentication via OpenID Connect.
OWIN on the other hand is a standard for web servers which decouples IIS and ASP.NET with the aim of allowing ASP.NET to run on other web servers which implement OWIN and other frameworks generally to run on OWIN compatible servers if those frameworks are OWIN compatible.
Auth0 is an identity platform which can do OAuth and allows you to use JWTs, generally it handles your identity and SSO. IdentityServer is another identity platform with some similar features.
I'd still recommend starting with the articles I linked at the top, don't worry too much about OWIN, and read more about OAuth to determine if you really need it. If you do, I'd recommend IdentityServer.

ASP.NET Core 2.0 and above Web API authentication and authorization
Bearer type JWT Token based authentication
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Please implement as following below post
https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Related

Implement authentication with token bearer and not cookie

How is it possible to implement authentication (and authorization) without cookie and only bearer token in ASP.Net MVC Core for all pages?
Can we still use ASP.Net Identity?
No, you can't use bearer token with MVC Views. Only with WebAPI-esque calls (which are called by JavaScript/Ajax calls), because for Bearer Token you need to pass a header containing the bearer token within the HTTP Request.
Also neither ASP.NET Core MVC nor ASP.NET Core Identity provide a mechanism to generate JWT or opaque/refresh tokens. You need a 3rd party library (ASOS, OpenIddict or IdentityServer4 - or write your own middleware).
General approach is using Cookies for MVC (+AntiForgery Tokens - these are important to prevent Cross-Site Forgery Requests (XSRF) attacks) and bearer for WebAPI (there are security concerns running Ajax/Rest calls with Cookies, as you can't easily protect then like you can do MVCs with AntiForgery tokens). In doubt, google about the terms ;)
Does it makes sense to you?
You could store the JWT in a cookieless Session - see Asp.net mvc 4 - Need to use sessions but can't use cookies
That sort of defeats the purpose of having JWT though.
You could ensure the JWT is a URL param in every link, and then override Application_AuthenticateRequest to find that in the URL and manually assign the identity to the context. see answer How to use JWT in MVC application for authentication and authorization?
Having multiple links with sizable JWT token data would add up. Also if one is missed in a chain of links, then the JWT would be "dropped". It's possible to save the JWT in the client-side sessionStore and have javascript dynamically add the JWT to links as they're clicked.

How to authenticate users of ASP.Net Core website with JWT?

I am wondering, if JWT should be attached to the header of my request manually, how can I use JWT to authenticate the users of my ASP.Net Core website?
In other words, how can I tell my browser to attach the token in the header when sending the request to my server? Let us say the user of my website got this token from one of my website's API.
Or is JWT usable only for WebAPI (where I can manually build the request)?
There are different ways to use JWT tokens. Since JWT is just a token format, it does imply the method used for authentication.
However, JWTs are mainly used for Bearer authentication scheme, which requires adding a custom header to each request. Single page applications (SPAs) that create requests in JavaScript on the client to access API endpoints can do that which is why Bearer+JWT is used a lot in SPAs. SPAs also benefit from the embedded JSON format since they can read expiration dates and other information (claims embedded in the token, ID token contents obtained via OpenID Connect etc.).
For "traditional" server-rendered views and links, using JWTs is hard since they'd have to be set as cookie or made part of the URL (practically impossible because of URL length restrictions). ASP.NET Core 2.0 does not contain any JWT-based cookie logic but it is possible to create a custom implementation using JWTs as cookies. See this GitHub project and related blog post for a sample implementation. Note that the only benefit of using JWTs in cookie authentication is that the server doesn't have to persist cookie information and share cookies across multiple instances.
To sum up the current state:
Prefer default cookie authentication when you use server-side rendering and links to avoid creating custom cookie implementations.
Prefer JWT bearer authentication if you have single page applications (SPAs) apps that build requests in javascript/typescript on the client.

ASP .NET Core Identity default authentication vs JWT authentication

I am developing ASP NET Core Web API and I am confused by choosing the authentication method. I used to apply default Asp Net Identity authentication, but recently I've known about JWT. So I've implemented Authentication almost as it done in this article: https://stormpath.com/blog/token-authentication-asp-net-core.
But I can't understand the benefits of this JWT. With simple Asp Net Identity Authentication, I don't care about token storage etc. I only need to log in with signInManager and use authorized methods until logout. With JWT I need to think about the token store, expiration, and other difficulties. So, what're the benefits of this JWT? How can I store this JWT token after login? Furthermore, should I even use this JWT? In my case, I need simple authentication for simple WebApi which will be used by one or little bit more users. I've also heard about OpenIddict, Auth0, IdentityServer, so what's the difference between all of these authentication mechanisms?
This is the way I understand this, split in to 3 logical parts.
Authentication Server - this will authenticate and issue the JWT token, when the API need's to validate the token it will send the token to this server to validate it.
Client - this is what serves your web pages, or you app perhaps. This is what will need to request and store the the JWT token. The client will need to pass the token to the api every time it requests data.
API - this is what serves the information and needs to validate the token with the Authentication Server.
So, what're the benefits of this JWT?
JWT is issued to the client and stored on the client side. Having JWT allows multiple client's (App's or Websites) use the same authentication server which distributes JWT and states which API's the client's can use and how.
How can I store this JWT token after login?
I only tried to store it in an Ionic 2 app which uses angular 2 which has a storage module. But i'm pretty sure numerous people have done this already and asked this question:
Simple JWT authentication in ASP.NET Core 1.0 Web API
Token Based Authentication in ASP.NET Core (refreshed)
Update
If your front end is made purely html/js/css and doesn't have a back end to accommodate it you would store your token in local storage, there a multiple npm packages that help you with this like this one. You want to look for Implicit flow.
Otherwise if you do have a back end that comes with your front end you want to store the token in a session/database your pick, there are 3rd party providers to do this like IdentityServer4. You want to use Hybrid flow
Furthermore, should I even use this JWT? In my case, I need simple
authentication for simple WebApi which will be used by one or little
bit more users.
The reason for the whole separation of concerns is performance so you don't really need it since it's just one or a little more users. Do it because it's a learning experience, JWT is not easy to setup from the beginning and will require you to do a lot of reading and you will fail and you will be frustrated but at the end you will know how to set it up and how it works
I've also heard about OpenIddict, Auth0, IdentityServer, so what's the difference between all of these authentication mechanisms?
So what you did in the Stormpath tutorial is NOT production ready. That is just a little demo, to help you understand what JWT is and how it works. The above mentioned are complete libraries that tackle all the heavy lifting and do not require you to built the whole thing from scratch. And the main difference between them is the scope that they cover.
I personally used IS4 and it had me crying no more than 2 times (It was simpler than I thought):
http://identityserver4.readthedocs.io/en/release/
https://github.com/openiddict/openiddict-core
https://auth0.com/docs/quickstart/webapp/aspnet-core/00-intro
Use tokens (JWT) if you have multiple applications or services (web, mobile, other services) connection to your API. Benefits: Stateless, Scalability, No cookie, no CORS problems (if you allow it).
If your API will be used by only one web application use the default ASP default authentication system. Its easier to set up.
If you webapi and user interface are hosted in the same web application, token bases security does not buy you anything over the cookie based authentication provided by the built in authentication. That's because the authentication cookie gets sent back to the keep application on every HTTP request. When you make calls to a website other than the one you signed in on those cookies do not get sent. So JSON Web Tokens (JWT) provide a standard format for browser to send identity information to a website when a cookie isn't an option.
If your Web Api is to be accessed by AJAX calls then JWT may be a desired choice, but not mandatory. judging by the description of your app,it seems to me that the default authentication system can serve you well.
Auth2 is the authentication mechanism that enable external login such as Facebook. It is part of the default authentication system, and you need not do much in order to employ it in your app.
OpenIddict sits on top of Auth2. It is part of the default authentication system, and you need not do much in order to employ it in your app. It is the authentication mechanism that enable external login such as Google+
IdentityServer may be used for large Wep Api that is accessed by Ajax calls. As for instance, you can use IdentityServer to authenticate users longing to a front end Angular app.
Once again, the default authentication system can serve you well.
Hope this helps...

What are the main differences between JWT and OAuth authentication?

I have a new SPA with a stateless authentication model using JWT. I am often asked to refer OAuth for authentication flows like asking me to send 'Bearer tokens' for every request instead of a simple token header but I do think that OAuth is a lot more complex than a simple JWT based authentication. What are the main differences, should I make the JWT authentication behave like OAuth?
I am also using the JWT as my XSRF-TOKEN to prevent XSRF but I am being asked to keep them separate? Should I keep them separate? Any help here will be appreciated and might lead to a set of guidelines for the community.
TL;DR
If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0. On the other hand, if there are lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.
As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format. It defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.
Being self-contained (the actual token contains information about a given subject), they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route, the only thing a party must present to be granted access to a protected resource is the token itself, and the token in question can be called a bearer token.
In practice, what you're doing can already be classified as bearer token -based. However, do consider you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply relying on the Authorization HTTP header and using the Bearer authentication scheme.
Regarding the use of the JWT to prevent CSRF: Without knowing exact details it's difficult to ascertain the validity of that practice. To be honest, it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.
One final piece of advice. Even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.
Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.
(source: RFC 6819, section 5.4.1)
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).
Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.
XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.
JWT (JSON Web Tokens)- It is just a token format. JWT tokens are JSON encoded data structures contains information about issuer, subject (claims), expiration time etc. It is signed for tamper proof and authenticity and it can be encrypted to protect the token information using symmetric or asymmetric approach. JWT is simpler than SAML 1.1/2.0 and supported by all devices and it is more powerful than SWT(Simple Web Token).
OAuth2 - OAuth2 solve a problem that user wants to access the data using client software like browse based web apps, native mobile apps or desktop apps. OAuth2 is just for authorization, client software can be authorized to access the resources on-behalf of end user using access token.
OpenID Connect - OpenID Connect builds on top of OAuth2 and add authentication. OpenID Connect add some constraint to OAuth2 like UserInfo Endpoint, ID Token, discovery and dynamic registration of OpenID Connect providers and session management. JWT is the mandatory format for the token.
CSRF protection - You don't need implement the CSRF protection if you do not store token in the browser's cookie.
It looks like everybody who answered here missed the moot point of OAUTH
From Wikipedia
OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.
The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access
There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points
You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general
Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials
find the main differences between JWT & OAuth
OAuth 2.0 defines a protocol & JWT defines a token format.
OAuth can use either JWT as a token format or access token which is a bearer token.
OpenID connect mostly use JWT as a token format.
JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.
Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.
You can read more on this here
OAuth or JWT? Which one to use and why?
Jwt is a strict set of instructions for the issuing and validating of signed access tokens. The tokens contain claims that are used by an app to limit access to a user
OAuth2 on the other hand is not a protocol, its a delegated authorization framework. think very detailed guideline, for letting users and applications authorize specific permissions to other applications in both private and public settings. OpenID Connect which sits on top of OAUTH2 gives you Authentication and Authorization.it details how multiple different roles, users in your system, server side apps like an API, and clients such as websites or native mobile apps, can authenticate with each othe
Note oauth2 can work with jwt , flexible implementation, extandable to different applications
JWT tokens require, at most, a one-time communication between the resource server and the authorization server at runtime. The
resource server needs to request the authorization server for the
public key to decrypt the JWT tokens. This can be done at resource
server startup. This can even be stored in the resource server in a
properties file avoiding the query at all.
OAuth2 solve a problem that user wants to access the data using client software like browser-based web apps, native mobile apps, or
desktop apps. OAuth2 is just for authorization, client software can
be authorized to access the resources on behalf of end-user using an
access token.
OAuth2 can be used with JWT tokens or access token which is a bearer
token.

ASP.Net Core RC2 JWT Bearer token

Does anyone have a complete example of using JWT bearer tokens with ASP.Net Core RC2 Identity? Preferably showing how to create the token also.
Thanks,
Paul
You may use OpenIdDict - a simple implementation of AspNet.Security.OpenIdConnect.Server.
Here and here is an example and article of using OpenIdDict.
Here is a discussion in Identity repo about JWT token authentication in ASP.Core
The official packages developed by Microsoft for ASP.NET Core only
support OAuth2 bearer token validation.
I'm personnaly using IdentityServer4 in ASP.NET core RC2 as an authentication app using JWT Bearer token. (very good Samples available) https://github.com/IdentityServer/IdentityServer4
For example : I have 3 projects (apps) in my solution
Login (IdentityServer4) that authenticate users and give them a JWT token when authenticated
API that is registered in IdentityServer4 as a consumer (Scope) for JWT tokens. Token attributes (Claims/Roles) are validated when accessing controller methods.
Web front end (Only HTML/AngularJS) that store the token and send it when sending a request (in the HTTP header) to the API. The front end is registered as "Client" in the Login
The big advantage to have an isolated Login app is that you can create as many API/front-end you want as long as you register them so they can communicate each other securely with the JWT token.
The samples available there https://github.com/IdentityServer/IdentityServer4.Samples are very straigtforward. If you have any question related to this project, feel free to ask.
I've ASP.NET Core 1.1 as backend and angular as front end solution with JWT bearer tokens. tokens can be easily created by lib.
https://github.com/Longfld/ASPNETcoreAngularJWT
I have a full example for ASP.NET Core with JWT auth: https://github.com/wilsonwu/netcoreauth
By the way, the database is SQL Server.