Token Authentication in ASP.NET Core--Stormpath Webinar

of 23/23
TOKEN AUTHENTICATI ON in ASP.NET Core Nate Barbettini @nbarbettini
  • date post

    07-Apr-2017
  • Category

    Technology

  • view

    105
  • download

    4

Embed Size (px)

Transcript of Token Authentication in ASP.NET Core--Stormpath Webinar

TOKEN AUTHENTICATIONin ASP.NET Core

Nate [email protected]

Welcome!

Agenda Stormpath 101 (5 mins) Get Started with iOS (40 mins) Q&A (10 mins)

Remy ChampionMarketing

Nate Barbettini.NET Developer Evangelist

Speed to Market & Cost Reduction

Complete Identity solution out-of-the-box Security best practices and updates by default Clean & elegant API/SDKs Little to code, no maintenance

Stormpath User Management

OverviewHow Sessions Work (And Why They Suck)How Token Authentication WorksTokens + ASP.NET Core

Intro - who I am: Stormpath .NET dev evangelist.

Stormpath is all about helping developers use best practices for security and providing tools to make it easier to build secure applications.

Ive had a chance to be on the bleeding edge with ASP.NET Core - lots of stuff has changed!

How Sessions Work

BrowserASP.NET(1) POST /login(2) 200 OKSet-Cookie: session=dh7jWkx8fj;(3) GET /profile(4) 200 OKCookie: session=dh7jWkx8fj;Log In:[email protected]!Open Profile PageProfit!Session Store

The browser POSTs the users credentials to your server. A session ID is created or updated that identifies the user.The session ID is pushed down to the browser inside a cookie.The cookie is included on each subsequent request. The session ID is used to find the session information in the session store (either in-memory or in a database).If the session lookup succeeds, the request is authenticated.

If the session store is in-memory, each user must stay on the server they started with.

Drawbacks of SessionsScaling is hard

Doesnt work with mobile

How Token Authentication Works

BrowserASP.NET(1) POST /login(2) 200 OKeyJ0eXAiOiJKV...Stored token: eyJ0eXAiOiJKV...(3) GET /profile(4) 200 OKAuthorization: Bearer eyJ0eXAiOiJKV...Log In:[email protected]!Open Profile ViewProfit!

The client POSTs the users credentials to your token endpoint. Your server generates a signed token that represents the users authentication ticket.The token is sent back to the client and stored somewhere locally.When the client needs to make another API request, it sends the token along with the request.Your API inspects the token to ensure it hasnt been tampered with. The token includes the information necessary to prove the user is authenticated. The server doesnt need to do any lookups.

Any server could have fulfilled the request, not just the one that the user authenticated with.

Advantages of Tokens

Stateless!

Works on both web and mobile

Flexible

The token itself contains enough information about the user, so the server doesnt need to look up their session in a session store.

A JWT is a JSON object thats been stringified and base64-encoded:Anatomy of JSON Web Tokens

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0NjU1ODAwNzEsImV4cCI6MTQ5NzExNjA3NywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoibmF0ZUBleGFtcGxlLmNvbSIsImlzQXdlc29tZSI6InRydWUiLCJwcm92aWRlcyI6WyJzdGF0ZWxlc3MiLCJhdXRoZW50aWNhdGlvbiJdfQ.VXrLbyQeJfDmwTAg-JnRsyD23RYMQJshTx79z2STu0URed = HeaderBlue = Payload (claims)Green = Cryptographic signature (JWS)

Its separated into two or three sections by periods.

Header: MetadataBody: Payload or claims

In this case, NOT encrypted.

Anatomy of JSON Web Tokens

{ typ: "JWT", alg: "HS256"}

{ iss: "Online JWT Builder", iat: 1465580071, exp: 1497116077, aud: "www.example.com", sub: "[email protected]", isAwesome: "true", provides: [ "stateless", "authentication" ]}

HeaderBody

You might be wondering: cant anyone just change these values?

Cryptographically signed by the server

Signature guarantees it hasnt been forged or alteredToken Security

Security needs to be airtight if we are going to implicitly trust something the client is sending us.

Token expiration (exp claim) and not-before (nbf claim)

Optional token revocation using a nonce (jti claim)

Use HTTPS (TLS) everywhere!

Store tokens securelyToken Security

Where to Store Tokens?On mobile: local device storage, sent via HTTP headers

On the web: cookies, or HTML5 web storage (via HTTP headers)

Where to Store Tokens?HTML5 web storage: vulnerable to XSS (cross-site scripting)

Cookies: not vulnerable to XSSSet the HttpOnly and Secure flagsStill need to protect against CSRF

More info: Stormpath bloghttps://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage

If I can get a malicious script to run on your page, I can do localStorage.getItem and grab your token.

Generating Tokens in ASP.NET CoreThis functionality was included in ASP.NET, but was removed from ASP.NET Core.

The community has stepped up to build this functionality:Stormpath ASP.NET Core pluginThinktecture IdentityServer4AspNet.Security.OpenIdConnect.ServerOpenIddict

Basic JWT creation: JwtSecurityTokenHandlerGenerating Tokens in ASP.NET Core

using System.IdentityModel.Tokens.Jwt;

var claims = new Claim[]{ new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),};

// Create the JWT and write it to a stringvar jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(5)), signingCredentials: _options.SigningCredentials);var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

Nates simple example on Github:https://github.com/nbarbettini/SimpleTokenProviderGenerating Tokens in ASP.NET Core

Validating Tokens in ASP.NET CoreValidating incoming Bearer (HTTP header) tokens is easy!

var mySecretKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes("mysupersecret_secretKey!123"));

app.UseJwtBearerAuthentication(new JwtBearerOptions(){ AutomaticAuthenticate = true, TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = mySecretKey, ValidateLifetime = true, ValidIssuer = "MyApplication", ValidAudience = "https://app.example.com", }});

Microsoft built a middleware component for this.

Great for mobile APIs.

Validating Tokens in ASP.NET CoreJWTs in cookies?See SimpleTokenProvider on Github.

Hosted user identity and authentication/authorization APIToken generation and authenticationSingle Sign-On across multiple applicationsMulti-tenant support for SaaS applicationsFree (forever) developer tierAbout Stormpath

Token authentication in ASP.NET Core tutorialhttps://stormpath.com/blog/token-authentication-asp-net-coreStormpath + ASP.NET Core quickstarthttps://docs.stormpath.com/dotnet/aspnetcore/latest/quickstart.htmlWeb storage vs. cookieshttps://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storageNates SimpleTokenProvider samplehttps://github.com/nbarbettini/SimpleTokenProvider

Q&A

Thank you!

Nate [email protected] .ws