Code Monkey home page Code Monkey logo

Comments (11)

galenp avatar galenp commented on July 19, 2024

To clarify... I have an authenticated end-user performing a request with a valid token set by IdentityServer implicit flow/

What I want to do is have my Nancy middleware being able to identify that the user is 'authenticated' and also be able to pull the users Id (and whatever else is in the claims).

I don't want to specifically build this up in Nancy itself as this same process would be required in other middleware that this app installs so I want to do it once at the top level.

from identityserver3.samples.

leastprivilege avatar leastprivilege commented on July 19, 2024

You need this to use the Katana authentication middleware from Nancy
https://github.com/damianh/Nancy.MSOwinSecurity

Ask Damian directly when there are more questions.

from identityserver3.samples.

galenp avatar galenp commented on July 19, 2024

Thank you for that reference Dominick .. this is useful as it shows me how to access the security context from within Nancy.

What about the correct configuration in my Startup.cs

Is there more beyond the UseIdentityServerJwt required?

from identityserver3.samples.

galenp avatar galenp commented on July 19, 2024

I'll answer my own question.

Nope nothing further required.

startup.cs

public void Configuration(IAppBuilder app)
        {         
            SecurityConfig.Register(app);                   
            app.UseNancy();
        }

ClaimsPrincipalExtensions.cs

 public static class ClaimsPrincipalExtensions
    {
        public static Guid CurrentUserId(this ClaimsPrincipal principal)
        {
            var subject = principal.Claims.GetClaimValue("sub");
            Guid userId;

            if (!Guid.TryParse(subject, out userId))
                throw new ApplicationException(String.Format("Invalid userid {0}", subject));

            return userId;
        }

        public static string GetClaimValue(this IEnumerable<Claim> claims, string type)
        {
            var claim = claims.FirstOrDefault(x => x.Type == type);

            return (claim != null ? claim.Value : null);
        }
    }

nancyModule

 this.RequiresMSOwinAuthentication();
var userId = Context.GetMSOwinUser().CurrentUserId();

from identityserver3.samples.

RPM1984 avatar RPM1984 commented on July 19, 2024

@galenp @leastprivilege is this information still relevant? I'm trying to get my Nancy API up and running with IS.. installed the Nancy.MSOwinSecurity package, but i can't find a reference to app.IdentityServerJwt or SecurityConfig.Register or app.UseJsonWebToken. It seems all these methods/techniques have been deprecated.

By the looks of the current methods and the samples i've read, i should be using app.UseIdentityServerBearerTokenAuthentication in a similar way to here

Can either of you advise and/or point me to the latest sample of how i should be setting up IdentityServer3 in Nancy?

from identityserver3.samples.

galenp avatar galenp commented on July 19, 2024

Just looking for you now @RPM1984 ...

from identityserver3.samples.

RPM1984 avatar RPM1984 commented on July 19, 2024

Thanks @galenp ! 😄 👏

from identityserver3.samples.

galenp avatar galenp commented on July 19, 2024

These are the packages I'm using.

  <package id="Nancy" version="1.2.0" targetFramework="net45" />
  <package id="Nancy.Hosting.Owin" version="0.16.0" targetFramework="net45" />
  <package id="Nancy.MSOwinSecurity" version="1.0.1" targetFramework="net45" />
  <package id="Nancy.Owin" version="1.2.0" targetFramework="net45" />
  <package id="System.IdentityModel.Tokens.Jwt" version="4.0.0" targetFramework="net45" />
  <package id="Thinktecture.IdentityModel.Client" version="4.0.1" targetFramework="net45" />
  <package id="Thinktecture.IdentityModel.Owin" version="1.0.0-beta1" targetFramework="net45" />
  <package id="Thinktecture.IdentityModel.Owin.ResourceAuthorization" version="1.0.1" targetFramework="net45" />
  <package id="Thinktecture.IdentityServer3.AccessTokenValidation" version="1.1.0" targetFramework="net45" />
  public static class SecurityConfig
    {
        public static void Register(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            //Token Check
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
            //    Provider = new EnhancedAuthenticationProvider(),
            //    AuthenticationMode = AuthenticationMode.Active
            //});

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                Authority = IdSvr.BaseAddress
            }); 

        }
    }

Registered in startup Configuration

  SecurityConfig.Register(app);

I've got this extension method

 public static class NancyModuleExtensions
  {
    public static bool HasAuthNancyUser(this INancyModule module)
    {
      return module.Context.CurrentUser != null && UserIdentityExtensions.IsAuthenticated(module.Context.CurrentUser);
    }

    public static void RequireKatanaAuthOtherwiseNancyAuth(this INancyModule module)
    {
      ModuleExtensions.AddBeforeHookOrExecute(module, (Func<NancyContext, Response>) (ctx =>
      {
        IAuthenticationManager authenticationManager = NancyContextExtensions.GetAuthenticationManager(ctx, false);
        if (authenticationManager == null || authenticationManager.User == null || !authenticationManager.User.Identity.IsAuthenticated)
        {
          if (NancyModuleExtensions.HasAuthNancyUser(module))
            return (Response) null;
          return (Response) HttpStatusCode.Unauthorized;
        }
        ctx.CurrentUser = (IUserIdentity) new NancyPropertyCompassUserIdentity(authenticationManager.User);
        return (Response) null;
      }), "Requires MS Owin authentication");
    }
  }

Which allows me to just add this in the constructor of each Nancy module

  this.RequireKatanaAuthOtherwiseNancyAuth();

And in each Nancy method you can do

 var user = Context.CurrentUser;

So from my recollection (and its been a while):

App is configured to validate incoming tokens with IdentityServer.

Requests to modules that have RequireKatanaAuthOtherwiseNancyAuth have a hook that validates that we have a identity in context.

from identityserver3.samples.

RPM1984 avatar RPM1984 commented on July 19, 2024

Awesome, i'll give this a try... thanks so much @galenp !

from identityserver3.samples.

DennisWelu avatar DennisWelu commented on July 19, 2024

Any thoughts or good samples for Nancy + IdentityServer4 all on NetCore? The part I feel I'm missing right now is a compatible rough equivalent to Nancy.MSOwinSecurity that works with NetCore.

from identityserver3.samples.

DennisWelu avatar DennisWelu commented on July 19, 2024

Just to tie off my question: http://stackoverflow.com/questions/43006280/nancy-and-identityserver4-on-net-core.

from identityserver3.samples.

Related Issues (20)

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.