Skip to content
This repository has been archived by the owner on Jul 19, 2021. It is now read-only.

Latest commit

 

History

History
52 lines (43 loc) · 1.86 KB

README.md

File metadata and controls

52 lines (43 loc) · 1.86 KB

The RedHttp project is no longer maintained. See Carter for a similar low-ceremony experience.

Jwt Sessions for RedHttpServer

Simple session management middleware for Red using JWT.Net

GitHub Nuget Nuget Dependent repos (via libraries.io)

Usage

After installing and referencing this library, the Red.Response has the extension method SendJwtToken(sessionData).

SendJwtToken(sessionData) creates a new Jwt token using the provided session-data and sends it JSON encoded: { "JWT": "Bearer eyJ0eXAiOiJKV1QiL..." }

Example

class Session
{
    public Guid UserId;
}
...
private static async Task<HandlerType> Auth(Request req, Response res)
{
    if (req.GetJwtData<Session>() == null)
    {
        await res.SendStatus(HttpStatusCode.Unauthorized);
        return HandlerType.Final;
    }
    return HandlerType.Continue;
}

static async Task Main(string[] args)
{
    var server = new RedHttpServer();
    server.Use(new JwtSessions<Session>(new JwtSessionSettings(TimeSpan.FromDays(5), "djklhfbaksdjhfajsdhfasdfhjadsb")));

    var data = new Session
    {
        UserId = Guid.NewGuid()
    };

    server.Get("/login", (req, res) => res.SendJwtToken(data));

    server.Get("/test", Auth, (req, res) =>
    {
        var sessionData = req.GetJwtData<Session>();
        return res.SendString("Hi " + sessionData.UserId);
    });

    await server.RunAsync();
}