The RedHttp project is no longer maintained. See Carter for a similar low-ceremony experience.
Simple session management middleware for Red using JWT.Net
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..." }
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();
}