Giter Club home page Giter Club logo

aspnetselfcreatedtokenauthexample's Introduction

ASP.NET Core Self-created token authentication example

A simple example of how to protect an ASP.NET Core Web API project using simple self-created JWT bearer tokens for local username/password checking. Working against dotnet core 1.0.1 as of 04/12/2016 - see the rc1, beta8 and beta7 branches if you're using older framework versions.

DO NOT USE AS-IS IN PRODUCTION

This example is to show the principles required to acheive local token authentication, and the following things should be changed before production usage:

  1. The random-generated private keys in Startup.cs should be changed and factored out to some sort of secure storage and shared amongst all app servers serving your site. Using the data protection API to ensure the keys are rotated and secured would be perfect, but I've not worked out how to do that yet (please submit a pull request if you get that working!).
  2. The error handling is very simple - and may leak application info to the end users as it returns the exception message.
  3. The username and password checking using an "if" statement should be replaced with checking against some sort of repository, and identities generated from that.
  4. Consider whether the token refresh strategy (the TokenController Get action) is appropriate for your application - this StackOverflow question and answer may help you decide what is best for your application

You can find more information about the principles in my StackOverflow answer here. This strategy is based on this StackOverflow answer to the same question by @mdekrey, updated for ASP.NET Core 1.0.1 and rationalised to be a slightly simpler, complete example.

aspnetselfcreatedtokenauthexample's People

Contributors

mrsheepuk avatar wierzba3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnetselfcreatedtokenauthexample's Issues

Is RSAParametersWithPrivate really required?

Hi,
I was making some tests with this project and I fail to understand the purpose of the RSAParametersWithPrivate class. It seems to me I can generate an RSAParameters object with all fields populated simply by deserializing it:

JsonConvert.DeserializeObject("");

The RSAParametersWithPrivate class does not seem to add anything to this. Am I missing something?

Integrating with ASP Core Identity..

Hi,

First thanks for such a great sample, you have no idea how long I have spent banging my head against this.

After getting this sample working I decided I want to try to integrate it into the standard ASP Core RC2 sample that comes with the latest Visual Studio.

I took your code and wove it in and to my great surprise it worked!

Now im trying to get it to work with the SQL DB that comes with the sample template. I have modified the TokenController Post function to look like this:

[HttpPost]
public async Task<dynamic> Post(string email, string password)
{
    var result = await _signInManager.PasswordSignInAsync(email, password, false, false);
    if (result.Succeeded)
    {
        DateTime? expires = DateTime.UtcNow.AddMinutes(2);
        var token = GetToken(email, expires);
        return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
    }

    return new { authenticated = false };
}

And that works well. Now I notice that in GetToken() you mention:

// Here, you should create or look up an identity for the user which is being authenticated.
// For now, just creating a simple generic identity.
var identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) });

Could you please explain a little about ClaimsIdentity, and Claims and how I should intergrate that with the ASP UserManager / SignInManager?

Thanks so much,
Mike

netcoreapp 1.0

.Net Core is released. I'm wondering if this project can be upgraded into netcoreapp1.0 framework instead of using dnx?

No SecurityTokenValidator available for token

Hello, I'm trying to play with this project (VS2015, ASPvNext RC), but I'm not able to access the secured API. Whenever I try a GET http://localhost:53129/api/value/1 I get the error No SecurityTokenValidator available for token:

{"success":false,"error":"No SecurityTokenValidator available for token: token=eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNyc2Etc2hhMjU2IiwidHlwIjoiSldUIn0.eyJuYmYiOjE0NTIxMDg2NTgsImV4cCI6MTQ1MjEwODc3OCwiaWF0IjoxNDUyMTA4NjU4LCJ1bmlxdWVfbmFtZSI6IlRFU1QiLCJFbnRpdHlJRCI6MSwiaXNzIjoiRXhhbXBsZUlzc3VlciIsImF1ZCI6IkV4YW1wbGVBdWRpZW5jZSJ9.LhAbTFL6_ESs6o9_Y_7s1K80EzOPhWIByTdDu-s6DkJx68pqclpWMVqpAEmGqPxKrCoG2EVoNvDYkvGhkqBMQ4J6I4KEcNt5ii1LwlxyCtPsBQ2Ez3WztTd9xMsGfIU0BtweJUhivviUI8m3Wp8pH-n94Mt5hjVNV0WQzHYYrZkzWrKlCX0o176N_M9P2sgJhxYFv1jD6gmQRGKPUNubH59R0WIlisu0pXL8_iF2FoQ-14bsvZ5wC40d3vLRxSVI-2EDQ2U6l4srsWfc0rWVAq1e5bRSn1LiX8DQ47VABpetYHSc62trx0ZLnAc6XmbeaTb2azbPY6LJAA0x2G5ulQ"}

Here is what I did:

  1. download your project, unzip and compile.
  2. run (F5) the solution.
  3. I can confirm that the server has started by accessing (using Fiddler) the unprotected API action with GET http://localhost:53129/api/values, which returns some JSON code.
  4. I request a token using the fake credentials TEST:TEST, and I correctly get it back with this post:
POST http://localhost:53129/api/token

--Header:
User-Agent: Fiddler
Host: localhost:5000
Content-type: application/json
Content-Length: 40

--Body:
{"username":"TEST", "password": "TEST" }
  1. I copy the received JWT token value and paste it into this request:
GET http://localhost:53129/api/value/1

--Header:
User-Agent: Fiddler
Host: localhost:53129
Content-Type: application/json
Authorization: Bearer token=...received token...

Yet, I always get the error quoted above. Any suggestion?

Sliding expiration for token

Hi,

Thank you for excellent demo application! This is really a time saver
Looks like current sample has fixed token expiration time. Is there any way to have this as sliding expiration?

Thank you

TokenController

I've been trying to get this sample to work. When/how is TokenController supposed to be called?

Authorize Roles

Is it possible to use this method to authorize a route based on the users role? I was able to put the roles into the claims just fine but when I attempt to add the Authorize attribute with the roles property set I get an unauthorized result back.

HMAC-SHA signing with secret

Hi,
thanks again for this excellent demo. I am trying to reduce the size of generated JWT tokens. At the moment, signature is more than 3 times the size of the payload. I think using HMACSHA256 signature with secret key could reduce the global token size.
I've tried to use it instead of RSA, but failed. Could you please improve your demo with this signing method? Thanks a lot!

Can't run

Got the following problem:

NU1001 The dependency Microsoft.AspNet.FileProviders.Physical >= 1.0.0-rc1-final could not be resolved. TokenAuthExampleWebApplication X:\dotnet\ASPNETSelfCreatedTokenAuthExample\src\TokenAuthExampleWebApplication\project.json 1

Running on CoreCLR on Linux

Did you manage to get this running on CoreCLR on Linux?

I tried on Ubuntu. I managed to get the creation of the key working by modifying the
lRsa = new RSACryptoServiceProvider(2048);
to
lRsa = new RSAOpenSsl(2048);

But I get into issues when trying to create a token, when the framework tries to create an AsymmetricSignatureProvider.

This seems to be this issue.

Has anyone tried anything like this yet?

Add a comment regarding middleware ordering

This is not any issue with your code really but more a help for others that, like me, didn't fully understood how the new middleware arhitecture works. I added app.UseJwtBearerAuthentication after app.useMvc() which resulted in an error saying that I had no authentication handler for Bearer. It took a while before I realised that, of course, the order of middlewares matters. So a comment in the code saying that app.UseJwtBearerAuthentication needs to come before asp.useMvc() could be helpful for others :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.