public async Task Invoke(HttpContext context, IJWTokenHelper helper)
        {
            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                var isAllowAnonymous = endpoint.Metadata.OfType <AllowAnonymousAttribute>().Count() > 0;
                if (isAllowAnonymous)
                {
                    await _next.Invoke(context);

                    return;
                }
            }
            var token = context.Request.Headers["Authorization"].FirstOrDefault();

            if (token == null)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                await context.Response.WriteAsync("");

                return;
            }

            var secretKey    = _configuration.GetValue <string>("Security:Secret");
            var isTokenValid = helper.DecodeJwToken(token, secretKey, out IEnumerable <Claim> claims);

            if (!isTokenValid)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Message = "Unknown Authentication" }));

                return;
            }

            foreach (var claim in claims)
            {
                context.Items.Add(claim.Type, claim.Value);
            }


            await _next.Invoke(context);
        }
Exemplo n.º 2
0
        public async Task <AuthOutput> Authenticate(string token, string secretKey)
        {
            var failed = new AuthOutput
            {
                Result = AuthMessage.AuthFailed
            };

            try
            {
                var result = _tokenHelper.DecodeJwToken(token, secretKey, out IEnumerable <Claim> claims);
                if (result == false)
                {
                    return(failed);
                }

                var id   = claims.First(x => x.Type == "uid").Value;
                var user = await _userRepo.GetUserById(Guid.Parse(id));

                if (user.IsDeleted == true)
                {
                    return(failed);
                }

                return(new AuthOutput
                {
                    Result = AuthMessage.AuthSuccess,
                    DisplayName = user.DisplayName,
                    JwToken = token
                });
            }
            catch (InvalidOperationException)
            {
                return(failed);
            }
            catch (Exception e)
            {
                throw e;
            }
        }