Coder Social home page Coder Social logo

nancy.oauth2's Introduction

Build status MyGet Prerelease NuGet Version

Nancy.OAuth2

A Nancy module for adding OAuth2 support.

Based on work by thecodejunkie

Nancy.OAuth2 is available via NuGet:

Install-Package Nancy.OAuth2

Getting Started

Note: In the following examples, IOAuthService and IUserService would be your own implementations

Install the module

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        // Default configuration for OAuth.Enable()
        OAuth.Enable(config =>
        {
            config.Base = "/oauth";
            config.AuthorizationRequestRoute = "/authorize";
            config.AuthorizationAllowRoute = "/allow";
            config.AuthorizationDenyRoute = "/deny";
            config.TokenRoute = "/token";
        });

        // If you are using the authorization_code grant, then register your implementation
        container.Register<IAuthorizationEndpointService, AuthorizationEndpointService>();

        // Register your implementation of the ITokenEndpointService
        container.Register<ITokenEndpointService, TokenEndpointService>();

        base.RequestStartup(container, pipelines, context);
    }
}

Create a class that implements the ITokenEndpointService interface.

public class TokenEndpointService : ITokenEndpointService
{
    private readonly IOAuthService _oauthService;
    private readonly IUserService _userService;

    public TokenEndpointService(
        IOAuthService oauthService,
        IUserService userService)
    {
        _oauthService = oauthService;
        _userService = userService;
    }

    public OAuthValidationResult ValidateRequest(TokenRequest request, NancyContext context)
    {
        if (!IsValidClient(request.ClientId, request.ClientSecret))
            return ErrorType.InvalidClient;

        // Only allow certain grant types
        switch (request.GrantType)
        {
            case GrantTypes.Password:
                return ValidatePasswordGrant(request);

            case GrantTypes.Authorization:
                return ValidateAuthorizationCodeGrant(request);

            default:
                return ErrorType.InvalidGrant;
        }
    }

    public TokenResponse CreateTokenResponse(TokenRequest request, NancyContext context)
    {
        // Build a token and store it somewhere so you can validate it later
        return BuildTokenResponse(request, context);
    }

    private bool IsValidClient(string clientId, string clientSecret)
    {
        var client = _oauthService.FindClientById(request.ClientId);

        return client != null && client.ClientSecret == clientSecret;
    }

    private OAuthValidationResult ValidatePasswordGrant(TokenRequest request)
    {
        var user = _userService.FindUserByUsername(request.Username);

        return user == null || user.HasValidPassword(request.Password)
            ? ErrorType.InvalidGrant
            : ErrorType.None;
    }

    private OAuthValidationResult ValidateAuthorizationCodeGrant(TokenRequest request)
    {
        var authCode = _oauthService.FindAuthorizationCode(request.Code);

        return authCode == null
            ? ErrorType.InvalidGrant
            : ErrorType.None;
    }
}

Authorization

If you want to enable the /authorize endpoints then you will need to create a class that implements the IAuthorizationEndpointService interface.

public class AuthorizationEndpointService : IAuthorizationEndpointService
{
    private readonly IOAuthService _oauthService;
    private readonly IUserService _userService;

    public AuthorizationEndpointService(
        IOAuthService oauthService,
        IUserService userService)
    {
        _oauthService = oauthService;
        _userService = userService;
    }

    public string GenerateAuthorizationToken(AuthorizationRequest request, NancyContext context)
    {
        var client = _oauthService.FindClientById(request.ClientId);
        var user = _userService.FindUserByUsername(context.CurrentUser.UserName);
        var authCode = _oauthService.CreateAuthCode(client, user);

        return authCode.Token;
    }

    public OAuthValidationResult ValidateRequest(AuthorizationRequest request, NancyContext context)
    {
        var client = _oauthService.FindClientById(request.ClientId);

        if (client == null)
            return ErrorType.InvalidClient;

        // Perform validation of the request for the client e.g.
        // - Is the RedirectUri allowed?
        // - Does it support the authorization_code grant?

        return ErrorType.None;
    }

    public Tuple<string, object> GetAuthorizationView(AuthorizationRequest request, NancyContext context)
    {
        var client = _oauthService.FindClientById(request.ClientId);
        var permissions = _oauthService.GetClientPermissions(request.ClientId);

        return new Tuple<string, object>("Authorize", new AuthorizeViewModel
        {
            Name = client.Name,
            Description = client.Description,
            Permissions = permissions
        });
    }
}

Any contributions will be greatly appreciated!

nancy.oauth2's People

Contributors

mrstebo avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

hopla

nancy.oauth2's Issues

Provide detailed tutorial

It would be really nice if you can provide a detailed tutorial from start to finish. Where you begin with a new project; go through installing and setting up Nancy with this library for use. It would help a great deal. I'm currently struggling to make this to work, but don't know if there are steps that i missed, or just did them wrong.

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.