GithubHelp home page GithubHelp logo

aloji / jwtsecurity Goto Github PK

View Code? Open in Web Editor NEW
17.0 4.0 5.0 59 KB

JWT Server for Asp.Net Core and Asp.Net WebAPI2

C# 100.00%
jwt-middleware jwt-server jwt-client jwt-token asp-net-core asp-net-web-api-2 netcore2 owin oauth2 aspnetcore

jwtsecurity's Introduction

Build status

JwtSecurity

The object is to allow using a token generated in an OWIN OAuth 2.0 Server in AspNet.Core projects.

Real life problem

We have the authorization server implemented with OWIN OAuth 2.0, but the new developments are with AspNetCore

The first idea was to use the machine keys

MachineKey

If the authorization server and the resource server are not on the same computer, the OAuth middleware will use the different machine keys to encrypt and decrypt bearer access token. In order to share the same private key between both projects, we add the same machinekey setting in both web.config files.

The problem is that machinekey does not exist in AspNetCore, but MS gives us a compatibility solution to replace the machinekey settings in AspNetWebApi2 and using a key storge provider like redis we can be shared the keys.

After several hours trying to implement this solution, I realized that it was easier, cleaner and cheaper to change the token generator to use JWT and dont use any external provider.

Configuration

How to setup the JwtSecurity in OWIN OAuth 2.0 Server (full sample code)

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AccessTokenFormat = new JwtSecureDataFormat(
                new JwtSecurityOptions
                {
                    Issuer = "yourIssuerCode",
                    IssuerSigningKey = "yourIssuerSigningKeyCode"
                })
        });
    }
}

How to setup the JwtSecurity in Resource Server .NetFramework (full sample code)

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AccessTokenFormat = new JwtSecureDataFormat(
                new JwtSecurityOptions
                {
                    Issuer = "yourIssuerCode",
                    IssuerSigningKey = "yourIssuerSigningKeyCode"
                })
        });
    }
}

How to setup the JwtSecurity in Resource Server .NetFramework with Owin Auth Compatibility

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AccessTokenFormat = new MachineKeyCompatibilityDataFormat(
                new JwtSecurityOptions
                {
                    Issuer = "yourIssuerCode",
                    IssuerSigningKey = "yourIssuerSigningKeyCode"
                })
        });
    }
}

How to setup the JwtSecurity in Resource Server .NetCore (full sample code)

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
              .AddJwtBearerAuthentication(options =>
              {
                  options.Issuer = "yourIssuerCode";
                  options.IssuerSigningKey = "yourIssuerSigningKeyCode";
              });
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
          app.UseAuthentication();
    }
}

Bonus:

I developed a middleware to create a JwtServer with AspNetCore very similar to OwinOAuth2 settings

How to setup the JwtServer in AspNetCore (full sample code)

 public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddJwtServer();
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
          app.UseJwtServer(options => {
                options.TokenEndpointPath = "/token";
                options.AccessTokenExpireTimeSpan = new TimeSpan(1, 0, 0);
                options.Issuer = "yourIssuerCode";
                options.IssuerSigningKey = "yourIssuerSigningKeyCode";
                options.AuthorizationServerProvider = new AuthorizationServerProvider
                {
                    OnGrantResourceOwnerCredentialsAsync = async (context) =>
                    {
                        if (context.UserName != context.Password)
                        {
                            context.SetError("Invalid user authentication");
                            return;
                        }

                        var claims = new List<Claim>
                        {
                            new Claim(ClaimTypes.Surname, context.UserName)
                        };

                        context.Validated(claims);
                        await Task.FromResult(0);
                    }
                };
            });
    }
}

jwtsecurity's People

Contributors

aloji avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

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.