private async Task InitBroker(HttpRequestMessage request)
        {
            // note! broker is mandatory in order to pull the server location

            try
            {
                var token = JWTGenerator.Utilities.GetTokenFromQuery(request);
                if (string.IsNullOrEmpty(token))
                {
                    token = JWTGenerator.Utilities.GetTokenFromHeader(request);
                }

                var generator    = new JWTGenerator(this.JWTSecretKey);
                var tokenPayload = generator.GetTokenPayload(token);
                var schema       = new
                {
                    BrokerName = "",
                    Role       = "",
                    RefName    = ""
                };
                var tokenPayloadModel = JsonConvert.DeserializeAnonymousType(tokenPayload, schema);
                this.BrokerName = tokenPayloadModel.BrokerName;
            }
            catch (Exception ex) {
                throw new StatusException(HttpStatusCode.Unauthorized, ex.Message);
            }
        }
Exemplo n.º 2
0
        public override void OnAuthorization(HttpActionContext context)
        {
            // Authorization: Bearer <token>

            try
            {
                // [AllowAnonymous]
                if (context.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
                {
                    base.OnAuthorization(context);
                    return;
                }

                var authorization = context.Request.Headers.Authorization;
                if (authorization == null)
                {
                    throw new HttpException((int)HttpStatusCode.Unauthorized, "No Authorization Header");
                }

                if (authorization.Scheme != "Bearer")
                {
                    throw new HttpException((int)HttpStatusCode.Unauthorized, "Not a Bearer Authorization");
                }

                var token     = authorization.Parameter;
                var generator = new JWTGenerator("my-secret-key");
                if (!generator.VerifyToken(token))
                {
                    throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized Access");
                }

                var header  = generator.GetTokenHeader(token);
                var payload = generator.GetTokenPayload(token);

                base.OnAuthorization(context);
            }
            catch (HttpException ex)
            {
                context.Response = new HttpResponseMessage((HttpStatusCode)ex.GetHttpCode())
                {
                    Content = new StringContent(ex.Message)
                };
            }
            catch (Exception ex)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent(ex.Message)
                };
            }
        }