Beispiel #1
0
        public Response Authorize(Request request)
        {
            ApiGatewayArn apiGatewayArn = null;
            string        principalId   = null;

            try
            {
                _logger.LogDebug("Authorizing");

                _requestValidationService.ValidateRequest(request, out apiGatewayArn);

                TokenValidationParameters jwtConfig = _tokenConfigService.GetJwtConfig();

                string          token = request.AuthorizationToken?.Replace("Bearer ", "");
                ClaimsPrincipal user  = _tokenValidationService.ValidateToken(token, jwtConfig);

                principalId = _claimsPrincipalService.GetPrincipalId(user);

                // this uses the all-or-nothing auth strategy by default:
                _policyBuilder.AllowAllMethods();

                // however, you could allow/deny specific methods/resources based off the user's claims, for example:
                // Claim role = user.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);
                // HttpVerb verb = role?.Value == "admin" ? HttpVerb.All : HttpVerb.Get;
                // _policyBuilder.AllowMethod(verb, "config");

                _logger.LogDebug("Authorization succeeded", new { principalId });
            }
            catch (BaseException ex)
            {
                _logger.LogDebug(ex.Message, new { ex.InnerException });
                _logger.LogDebug("Authorization failed", new { });

                // you may choose to throw an unauthorized exception here instead of returning a "deny all" policy
                // throw new UnauthorizedException();

                _policyBuilder.DenyAllMethods();
            }

            Response response = _policyBuilder.Build(apiGatewayArn, principalId);

            // you can add key-value pairs that can be accessed in API Gateway via $context.authorizer.<key>
            // response.Context.Add("key", "value");

            return(response);
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            if (context.User != null && _state.LoggedUser == null)
            {
                var my = await _esquioHttpClient.GetMy();

                if (my != null && !String.IsNullOrEmpty(my.ActAs))
                {
                    var loggedUser = new LoggedUserViewModel()
                    {
                        UserName  = context.User.Identity.Name,
                        SubjectId = context.User.FindFirst("sub").Value,
                        ActAs     = my.ActAs
                    };

                    var policy = _policyBuilder.Build(my);

                    _state.ClearState();
                    _state.SetLoggedUser(loggedUser);
                    _state.SetPolicy(policy);
                }
                else
                {
                    context.Fail();
                    return;
                }
            }

            var actAs = ActAs.From(_state.LoggedUser.ActAs);

            bool allowed = requirement.Permission switch
            {
                Policies.Reader => actAs == ActAs.Reader || actAs == ActAs.Contributor || actAs == ActAs.Management,
                Policies.Contributor => actAs == ActAs.Contributor || actAs == ActAs.Management,
                Policies.Management => actAs == ActAs.Management,
                _ => throw new ArgumentNullException("The configured authorization policy is not supported.")
            };

            if (!allowed)
            {
                LogAuthorizationFailed(_state.LoggedUser.SubjectId, requirement.Permission);
                context.Fail();
            }

            context.Succeed(requirement);
        }
 public IPolicy Create() => _builder.Build();