Coder Social home page Coder Social logo

unosquare / embedio-extras Goto Github PK

View Code? Open in Web Editor NEW
44.0 25.0 16.0 2.06 MB

Additional Modules showing how to extend EmbedIO.

Home Page: http://unosquare.github.io/embedio-extras/

License: Other

C# 100.00%
owin middleware json webserver sqlite3 bearer json-server embedio-modules

embedio-extras's Introduction

** THIS REPO HAS BEEN ARCHIVED **

Build status Buils status

EmbedIO Extras

EmbedIO

โญ Please star this project if you find it useful!

Additional Modules showing how to extend EmbedIO. Feel free to use these modules in your projects.

Bearer Token Module

Provides the ability to authenticate requests via a Bearer Token. This module creates a Token endpoint (at the predefined '/token' path) and all you need to do is provide a user validation delegate which authenticates the user. The module will create a JsonWebToken which can then be used by your client application for further requests. The module can check all incoming requests or a predefined set of paths. The standard header in use is the HTTP Authorization header.

You can easily add Bearer Token to your EmbedIO application using the default Basic Authorization Server Provider or writing your own by implementing IAuthorizationServerProvider interface.

The following example will attach Bearer Token to the Web server in the "/api" base route and then a WebAPI Controller using the same base route.

// Create Webserver and attach the Bearer Token Module
var server = new WebServer(url)
                .WithBearerToken("/api", "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF")
                .WithWebApi("/api", o => o.WithController<SecureController>());

Nuget installation NuGet version

PM> Install-Package EmbedIO.BearerToken

Json Server Module

Based on the JsonServer's project, with this module, you are able to simply specify a JSON file as a database and use standard REST methods to create, update, retrieve and delete records from it.

// Create Webserver and attach JsonServerModule
var server = new WebServer(url)
                .WithModule(new JsonServerModule(jsonPath: Path.Combine(WebRootPath, "database.json");               

Supported methods:

  • GET collection (http://yourhost/entity)
  • GET single (http://yourhost/entity/1 where 1 is the ID)
  • POST (http://yourhost/entity with POST body the JSON object)
  • PUT (http://yourhost/entity/1 with POST body the JSON object)
  • DELETE (http://yourhost/entity/1 where 1 is the ID)

LiteLib WebAPI

Similar to Json Server Module, but you can serve an SQLite file with all HTTP verbs using LiteLib library.

// Create Webserver and attach LiteLibModule with a LiteLib DbContext
var server = new WebServer(url)
                .WithModule(new LiteLibModule<TestDbContext>(new TestDbContext(), "/dbapi"));
                
 internal class TestDbContext : LiteDbContext
    {
        public TestDbContext()
            : base("dbase.db")
        {
            // Need to Define the tables Create  dyanmic types ?
        }

    }                
                

Supported methods:

  • GET collection (http://yourhost/entity)
  • GET single (http://yourhost/entity/1 where 1 is the ID)
  • POST (http://yourhost/entity with POST body the JSON object)
  • PUT (http://yourhost/entity/1 with POST body the JSON object)
  • DELETE (http://yourhost/entity/1 where 1 is the ID)

Markdown Static Module

The Markdown Static Module takes in a static Markdown file and converts it into HTML before returning a response. It will accept markdown/html/htm extensions (This could become middleware later).

// Create Webserver and attach Markdown Static Module
var server = new WebServer(url)
               .WithModule(new MarkdownStaticModule("/", WebRootPath));

embedio-extras's People

Contributors

chubbsnes65 avatar dependabot-preview[bot] avatar geoperez avatar greciaveronica avatar israelramosm avatar k3z0 avatar mariodivece avatar neilsilver 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

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

embedio-extras's Issues

Add license

Hey, thanks for this awesome lib!
Could you please add a license file to this project?

Update Readme.md and Litelib sample with examples of usage compatible with EmbedIO v3

The readme.Md examples (apart from the auth token) are not compatible with the extension methods of v3.

I will fork and do some work on updating the readme myself.

The documentation here : https://unosquare.github.io/embedio-extras/#litelib is also similar.

In addition there is no Litelib in the Sample and it has the most specific implementation. So could do with adding the

Lastly it is not clear that the EmbedIO.LiteLibWebApi on Nuget https://www.nuget.org/packages/EmbedIO.LiteLibWebApi/
Is Not compatible with EmbedIOv3

System.MissingMethodeException

Hello,

i have the error:

System.MissingMethodException: "Missing Method "Void Unosquare.Labs.EmbedIO.WebModuleBase.AddHandler(System.String, Unosquare.Labs.EmbedIO.HttpVerbs, System.Func`3<System.Net.HttpListenerContext,System.Threading.CancellationToken,System.Threading.Tasks.Task`1<Boolean>>)"."

with this code:

            var basicAuthProvider = new BasicAuthorizationServerProvider();
            var routes = new[] { "/secure.html" };

            var server = new WebServer("http://localhost:9696/", RoutingStrategy.Regex);
     
            server.RegisterModule(new BearerTokenModule(basicAuthProvider, routes));
            server.RegisterModule(new WebApiModule());

            server.Module<WebApiModule>().RegisterController<RequestController>();
            server.RunAsync();

Could you please help me? What is wrong?

cannot convert from 'Unosquare.Labs.EmbedIO.BearerToken.BearerTokenModule' to 'Unosquare.Labs.EmbedIO.IWebModule'

Hi,
My .Net 4.5 app is using EmbedIO 1.0.19 and EmbedIO.BearerToken 1.0.0 packages from nuget. With this code:

            var basicAuthProvider = new BasicAuthorizationServerProvider();
            var routes = new[] { "" };
            server.RegisterModule(new BearerTokenModule(basicAuthProvider, routes));

I get error: cannot convert from 'Unosquare.Labs.EmbedIO.BearerToken.BearerTokenModule' to 'Unosquare.Labs.EmbedIO.IWebModule'

How can I correct it?

Token generated with BearerTokenModule has incorrect expiry time

The bearer token generated has a different expiry date to that what was requested by the service provider.

await context.JsonResponseAsync(new BearerToken
                    {
                        Token = validationContext.GetToken(SecretKey),
                        TokenType = "bearer",
                        ExpirationDate = authorizationServerProvider.GetExpirationDate(),
                        Username = validationContext.IdentityName,
                    });

where the line

   validationContext.GetToken(SecretKey)

creates a token with a default expiry date.

I did the following to fix the issue

                if (validationContext.IsValidated)
                {
                    var expiryDate = DateTime.SpecifyKind(DateTime.FromBinary(authorizationServerProvider.GetExpirationDate()), DateTimeKind.Utc);

                    await context.JsonResponseAsync(new BearerToken
                    {
                        Token = validationContext.GetToken(SecretKey, expiryDate),
                        TokenType = "bearer",
                        ExpirationDate = authorizationServerProvider.GetExpirationDate(),
                        Username = validationContext.IdentityName,
                    });
                }
...

        public string GetToken(SymmetricSecurityKey secretKey, DateTime? expires = null)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var plainToken = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Subject = Identity,
                Issuer = "Embedio Bearer Token",
                Expires = expires,
                SigningCredentials = new SigningCredentials(secretKey,
                    SecurityAlgorithms.HmacSha256Signature),
            });

            return tokenHandler.WriteToken(plainToken);
        }

I hope this helps.

How to setup the principal in EmbedIO with bearer token and API modules

I'm using the Bearer Token Module to secure the API module.

How can I get the IHttpContext.User property set to the current user, so that I can access it in my controllers?

Here's the relevant part of the web server setup:

WebServerEmbedded
    .WithCors()
    .WithBearerToken("/api", "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF", new MyAuthorizationServerProvider())
    .WithModule(webApiModule)

and here is MyAuthorizationServerProvider:

internal sealed class MyAuthorizationServerProvider: IAuthorizationServerProvider
{
    public async Task ValidateClientAuthentication(ValidateClientAuthenticationContext context)
    {
        var data = await context.HttpContext.GetRequestFormDataAsync().ConfigureAwait(false);

        if (data?.ContainsKey("grant_type") == true && data["grant_type"] == "password")
        {
            var username = data.ContainsKey("username") ? data["username"] : string.Empty;
            var password = data.ContainsKey("password") ? data["password"] : string.Empty;

            if (ValidateCredentials(username, password))
            {
                context.Validated(username);
            }
            else
            {
                context.Rejected();
            }
        }
        else
        {
            context.Rejected();
        }
    }

    public long GetExpirationDate() => DateTime.UtcNow.AddHours(12).Ticks;

    private static bool ValidateCredentials(string username, string password)
    {
        var user = BusinessLayer.CheckUserAndPassword(username, password);
        return user != null;
    }
}

Thanks.

Bearer Token routes not working with WebApiController routes

It looks like routes passed to BearerTokenModule are not working with WebApiController routes.

It works if API Controller routes and Bearer token routes are as follows :

  • route begin with "/" and there should NOT be anymore "/"
  • route is just wildcard "*"
  • route is null (default)

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.