Esempio n. 1
0
        private async Task OnTokenRequest(IHttpContext context)
        {
            context.SetHandled();

            var validationContext = context.GetValidationContext();
            await _authorizationServerProvider.ValidateClientAuthentication(validationContext)
            .ConfigureAwait(false);

            if (!validationContext.IsValidated)
            {
                context.Rejected(validationContext.ErrorPayload);
                return;
            }

            var expiryDate = DateTime.SpecifyKind(
                DateTime.FromBinary(_authorizationServerProvider.GetExpirationDate()),
                DateTimeKind.Utc);

            var token = new BearerToken
            {
                Token          = validationContext.GetToken(SecretKey, expiryDate),
                TokenType      = "bearer",
                ExpirationDate = _authorizationServerProvider.GetExpirationDate(),
                Username       = validationContext.IdentityName,
            };

            var dictToken = Json.Deserialize <Dictionary <string, object> >(Json.Serialize(token));

            OnSuccessTransformation?.Invoke(dictToken);

            await context
            .SendDataAsync(dictToken)
            .ConfigureAwait(false);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BearerTokenModule"/> class.
        /// </summary>
        /// <param name="authorizationServerProvider">The authorization server provider.</param>
        /// <param name="routes">The routes.</param>
        /// <param name="secretKey">The secret key.</param>
        /// <param name="endpoint">The endpoint.</param>
        public BearerTokenModule(
            IAuthorizationServerProvider authorizationServerProvider,
            IEnumerable <string> routes    = null,
            SymmetricSecurityKey secretKey = null,
            string endpoint = "/token")
        {
            // TODO: Make secretKey parameter mandatory and and an overload that takes in a string for a secretKey
            SecretKey = secretKey ?? new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF"));

            AddHandler(endpoint, HttpVerbs.Post, async(context, ct) =>
            {
                var validationContext = context.GetValidationContext();
                await authorizationServerProvider.ValidateClientAuthentication(validationContext);

                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,
                    });
                }
                else
                {
                    context.Rejected();
                }

                return(true);
            });

            AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (context, ct) =>
            {
                if (routes != null)
                {
                    var match = Match(routes, context);

                    if (!match)
                    {
                        return(Task.FromResult(false));
                    }
                }

                // decode token to see if it's valid
                if (context.GetSecurityToken(SecretKey) != null)
                {
                    return(Task.FromResult(false));
                }

                context.Rejected();

                return(Task.FromResult(true));
            });
        }
        /// <summary>
        /// Module's Constructor
        /// </summary>
        /// <param name="authorizationServerProvider">The AuthorizationServerProvider to use</param>
        /// <param name="routes">The routes to authorizate</param>
        /// <param name="secretKey">The secret key to encrypt tokens</param>
        public BearerTokenModule(IAuthorizationServerProvider authorizationServerProvider,
                                 IEnumerable <string> routes = null, string secretKey = "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF")
        {
            AddHandler("/token", HttpVerbs.Post, (server, context) =>
            {
                var validationContext = context.GetValidationContext();
                authorizationServerProvider.ValidateClientAuthentication(validationContext);

                if (validationContext.IsValidated)
                {
                    context.JsonResponse(new BearerToken
                    {
                        Token          = validationContext.GetToken(secretKey),
                        TokenType      = "bearer",
                        ExpirationDate = authorizationServerProvider.GetExpirationDate(),
                        Username       = validationContext.ClientId
                    });
                }
                else
                {
                    context.Rejected();
                }

                return(true);
            });

            AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (server, context) =>
            {
                if (routes != null && routes.Contains(context.RequestPath()) == false)
                {
                    return(false);
                }

                var authHeader = context.RequestHeader(AuthorizationHeader);

                if (string.IsNullOrWhiteSpace(authHeader) == false && authHeader.StartsWith("Bearer "))
                {
                    try
                    {
                        var token   = authHeader.Replace("Bearer ", "");
                        var payload = JWT.JsonWebToken.DecodeToObject(token, secretKey) as IDictionary <string, object>;

                        if (payload == null || payload.Count == 0)
                        {
                            throw new Exception("Invalid token");
                        }

                        return(false);
                    }
                    catch (JWT.SignatureVerificationException)
                    {
                        server.Log.DebugFormat("Invalid token {0}", authHeader);
                        throw;
                    }
                    catch (Exception ex)
                    {
                        server.Log.Error(ex);
                    }
                }

                context.Rejected();

                return(true);
            });
        }