Beispiel #1
0
 public JwtSecurityContextFactory(
     ICallContextFactory callContextFactory, ILoopbackIpFilter loopbackIpFilter, IJwtTokenReader jwtTokenReader)
 {
     _callContextFactory = callContextFactory.ThrowIfNull(nameof(callContextFactory));
     _loopbackIpFilter   = loopbackIpFilter.ThrowIfNull(nameof(loopbackIpFilter));
     _jwtTokenReader     = jwtTokenReader.ThrowIfNull(nameof(jwtTokenReader));
 }
        public AzureManagedIdentityAuthorizationFilter(IJwtTokenReader jwtTokenReader)
        {
            Guard.NotNull(jwtTokenReader, nameof(jwtTokenReader));

            _headerName     = DefaultHeaderName;
            _jwtTokenReader = jwtTokenReader;
        }
        private async Task ValidateJwtTokenAsync(IJwtTokenReader reader, AuthorizationFilterContext context, StringValues jwtString, ILogger logger)
        {
            if (String.IsNullOrWhiteSpace(jwtString))
            {
                LogSecurityEvent(logger, "Cannot validate JWT MSI token because the token is blank", HttpStatusCode.Unauthorized);
                context.Result = new UnauthorizedObjectResult("Blank JWT MSI token");

                return;
            }

            if (!JwtRegex.IsMatch(jwtString))
            {
                LogSecurityEvent(logger, "Cannot validate JWT MSI token because the token is in an invalid format", HttpStatusCode.Unauthorized);
                context.Result = new UnauthorizedObjectResult("Invalid JWT MSI token format");

                return;
            }

            bool isValidToken = await reader.IsValidTokenAsync(jwtString);

            if (isValidToken)
            {
                LogSecurityEvent(logger, "JWT MSI token is valid");
            }
            else
            {
                LogSecurityEvent(logger, "JWT MSI token is invalid", HttpStatusCode.Unauthorized);
                context.Result = new UnauthorizedObjectResult("Wrong JWT MSI token");
            }
        }
        /// <summary>
        /// Called early in the filter pipeline to confirm request is authorized.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext" />.</param>
        /// <returns>
        ///     A <see cref="T:System.Threading.Tasks.Task" /> that on completion indicates the filter has executed.
        /// </returns>
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            Guard.NotNull(context, nameof(context));
            Guard.NotNull(context.HttpContext, nameof(context.HttpContext));
            Guard.For <ArgumentException>(() => context.HttpContext.Request is null, "Invalid action context given without any HTTP request");
            Guard.For <ArgumentException>(() => context.HttpContext.Request.Headers is null, "Invalid action context given without any HTTP request headers");
            Guard.For <ArgumentException>(() => context.HttpContext.RequestServices is null, "Invalid action context given without any HTTP request services");

            ILogger logger = context.HttpContext.RequestServices.GetLoggerOrDefault <JwtTokenAuthorizationFilter>();

            if (context.ActionDescriptor?.EndpointMetadata?.Any(m => m is BypassJwtTokenAuthorizationAttribute || m is AllowAnonymousAttribute) == true)
            {
                logger.LogTrace("Bypass JWT authorization on this path because the '{SpecificAttribute}' of '{GeneralAttribute}' was found", nameof(BypassJwtTokenAuthorizationAttribute), nameof(AllowAnonymousAttribute));
                return;
            }

            IJwtTokenReader reader = _authorizationOptions.GetOrCreateJwtTokenReader(context.HttpContext.RequestServices);

            if (reader is null)
            {
                logger.LogError("Cannot validate JWT MSI token because no '{Type}' was registered in the options of the JWT authorization filter", nameof(IJwtTokenReader));
                throw new InvalidOperationException("Cannot validate JWT MSI token because the registered JWT options were invalid");
            }

            if (context.HttpContext.Request.Headers.TryGetValue(_authorizationOptions.HeaderName, out StringValues jwtString))
            {
                await ValidateJwtTokenAsync(reader, context, jwtString, logger);
            }
            else
            {
                LogSecurityEvent(logger, "No JWT MSI token was specified in the request", HttpStatusCode.Unauthorized);
                context.Result = new UnauthorizedObjectResult("No JWT MSI token header found in request");
            }
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JwtTokenAuthorizationOptions"/> class.
        /// </summary>
        /// <param name="reader">The JWT reader to verify the token from the HTTP request header.</param>
        /// <param name="headerName">The name of the header where the JWT token is expected.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="reader"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown when the <paramref name="headerName"/> is blank.</exception>
        public JwtTokenAuthorizationOptions(IJwtTokenReader reader, string headerName)
        {
            Guard.NotNull(reader, nameof(reader), $"Requires a valid {nameof(IJwtTokenReader)} to verify the JWT token");
            Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank request header name to look for the JWT token");

            JwtTokenReader = reader;
            HeaderName     = headerName;
        }
Beispiel #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JwtTokenAuthorizationOptions"/> class.
 /// </summary>
 /// <param name="reader">The JWT reader to verify the token from the HTTP request header.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="reader"/> is <c>null</c>.</exception>
 public JwtTokenAuthorizationOptions(IJwtTokenReader reader)
     : this(reader, DefaultHeaderName)
 {
 }