Ejemplo n.º 1
0
        /// <summary>
        /// Adds the <see cref="JwtAuthorizationManager"/> to a <see cref="ServiceHost"/>
        /// </summary>
        /// <param name="serviceHost">Your service to be secured with JWT Auth</param>
        /// <param name="configuration">Your application configuration, including VCAP_SERVICES</param>
        /// <param name="httpClient">Provide your own http client for interacting with the security server</param>
        /// <param name="loggerFactory">For logging within the library</param>
        /// <returns>Your service</returns>
        public static ServiceHost AddJwtAuthorization(this ServiceHost serviceHost, IConfiguration configuration, HttpClient httpClient = null, LoggerFactory loggerFactory = null)
        {
            if (serviceHost == null)
            {
                throw new ArgumentNullException(nameof(serviceHost));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // get options with defaults
            var cloudFoundryOptions = new CloudFoundryOptions(loggerFactory);

            // get and apply config from application
            var securitySection = configuration.GetSection(CloudFoundryDefaults.SECURITY_CLIENT_SECTION_PREFIX);

            securitySection.Bind(cloudFoundryOptions);

            // get and apply service binding info
            SsoServiceInfo info = configuration.GetSingletonServiceInfo <SsoServiceInfo>();

            CloudFoundryOptionsConfigurer.Configure(info, cloudFoundryOptions);

            var authManager = new JwtAuthorizationManager(cloudFoundryOptions);

            serviceHost.Authorization.ServiceAuthorizationManager = authManager;

            return(serviceHost);
        }
        public CloudFoundryWcfTokenValidator(CloudFoundryOptions options, ILogger <CloudFoundryTokenValidator> logger = null)
            : base(options)
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));

            // alwaus use the same static logger
#pragma warning disable S3010 // Static fields should not be updated in constructors
            _logger = logger;
#pragma warning restore S3010 // Static fields should not be updated in constructors
        }
Ejemplo n.º 3
0
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            HttpRequestMessageProperty httpRequestMessage;

            if (operationContext.RequestContext.RequestMessage.Properties.TryGetValue(HttpRequestMessageProperty.Name, out object httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                if (string.IsNullOrEmpty(httpRequestMessage.Headers["Authorization"]))
                {
                    CloudFoundryTokenValidator.ThrowJwtException("No Authorization header", null);
                }

                // Get Bearer token
                if (!httpRequestMessage.Headers["Authorization"].StartsWith("Bearer "))
                {
                    CloudFoundryTokenValidator.ThrowJwtException("No Token", null);
                }

                string jwt = httpRequestMessage.Headers["Authorization"].Split(' ')[1];
                if (string.IsNullOrEmpty(jwt))
                {
                    CloudFoundryTokenValidator.ThrowJwtException("Wrong Token Format", null);
                }

                // Get SSO Config
                Options = Options ?? new CloudFoundryOptions();
                if (Options.OAuthServiceUrl == null || Options.OAuthServiceUrl.Length == 0)
                {
                    CloudFoundryTokenValidator.ThrowJwtException("SSO Configuration is missing", null);
                }

                // Validate Token
                ClaimsPrincipal claimsPrincipal = Options.TokenValidator.ValidateToken(jwt);
                if (claimsPrincipal == null)
                {
                    return(false);
                }

                // Set the Principal created from token
                SetPrincipal(operationContext, claimsPrincipal);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
        private string GetAccessToken()
        {
            CloudFoundryOptions options = new CloudFoundryOptions();

            CloudFoundryClientTokenResolver tokenResolver = new CloudFoundryClientTokenResolver(options);

            try
            {
                string accessToken = tokenResolver.GetAccessToken().GetAwaiter().GetResult();

                return(accessToken);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message + ex.StackTrace);
                throw new Exception("Cannont obtain the Access Token" + ex.Message);
            }
        }
        /// <summary>
        /// Apply service binding info to an <see cref="CloudFoundryOptions"/> instance
        /// </summary>
        /// <param name="si">Service binding information</param>
        /// <param name="options">CloudFoundryOptions options to be updated</param>
        internal static void Configure(SsoServiceInfo si, CloudFoundryOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (si == null)
            {
                return;
            }

            options.AuthorizationUrl = si.AuthDomain;
            options.ClientId         = si.ClientId;
            options.ClientSecret     = si.ClientSecret;

            var backchannelHttpHandler = CloudFoundryHelper.GetBackChannelHandler(options.ValidateCertificates);

            options.TokenValidationParameters = CloudFoundryHelper.GetTokenValidationParameters(options.TokenValidationParameters, options.AuthorizationUrl + CloudFoundryDefaults.JwtTokenUri, backchannelHttpHandler, options.ValidateCertificates, options);
        }
Ejemplo n.º 6
0
        internal static TokenValidationParameters GetTokenValidationParameters(CloudFoundryOptions options)
        {
            if (options.TokenValidationParameters != null)
            {
                return(options.TokenValidationParameters);
            }

            var parameters = new TokenValidationParameters();

            options.TokenKeyResolver          = options.TokenKeyResolver ?? new CloudFoundryTokenKeyResolver(options);
            options.TokenValidator            = options.TokenValidator ?? new CloudFoundryTokenValidator(options);
            options.TokenValidationParameters = parameters;

            parameters.ValidateAudience = options.ValidateAudience;
            parameters.ValidateIssuer   = options.ValidateIssuer;
            parameters.ValidateLifetime = options.ValidateLifetime;

            parameters.IssuerSigningKeyResolver = options.TokenKeyResolver.ResolveSigningKey;
            parameters.IssuerValidator          = options.TokenValidator.ValidateIssuer;
            parameters.AudienceValidator        = options.TokenValidator.ValidateAudience;

            return(parameters);
        }
 public JwtHeaderMessageInspector(CloudFoundryOptions options, string userToken, HttpClient httpClient = null)
 {
     _options    = options;
     _userToken  = userToken;
     _httpClient = httpClient;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudFoundryClientTokenResolver"/> class.
 /// This class can be used to get access tokens from an OAuth server
 /// </summary>
 /// <param name="options">Con</param>
 /// <param name="httpClient">For interacting with the OAuth server. A new instance will be created if not provided.</param>
 public CloudFoundryClientTokenResolver(CloudFoundryOptions options, HttpClient httpClient = null)
 {
     Options         = options ?? throw new ArgumentNullException(nameof(options), "Options are required");
     _tokenExchanger = new TokenExchanger(options, httpClient, options.LoggerFactory?.CreateLogger <TokenExchanger>());
     _logger         = Options.LoggerFactory?.CreateLogger <CloudFoundryClientTokenResolver>();
 }
Ejemplo n.º 9
0
 public CloudFoundryWcfTokenValidator(CloudFoundryOptions options, ILogger <CloudFoundryTokenValidator> logger = null)
     : base(options)
 {
     Options = options ?? throw new ArgumentNullException(nameof(options));
     _logger = logger;
 }
Ejemplo n.º 10
0
 public JwtHeaderEndpointBehavior(CloudFoundryOptions options, string userToken = null)
 {
     _options   = options;
     _userToken = userToken;
 }
Ejemplo n.º 11
0
 public CloudFoundryTokenKeyResolver(CloudFoundryOptions options, HttpClient httpClient = null)
 {
     Options     = options ?? throw new ArgumentNullException(nameof(options));
     Resolved    = new Dictionary <string, SecurityKey>();
     _httpClient = httpClient ?? HttpClientHelper.GetHttpClient(options.ValidateCertificates, options.ClientTimeout);
 }
Ejemplo n.º 12
0
 public JwtHeaderMessageInspector(CloudFoundryOptions options, string userToken)
 {
     _options   = options;
     _userToken = userToken;
 }
Ejemplo n.º 13
0
 public JwtAuthorizationManager(CloudFoundryOptions options)
     : base()
 {
     _options = options;
 }
Ejemplo n.º 14
0
 public CloudFoundryClientTokenResolver(CloudFoundryOptions options)
 {
     Options = options ?? throw new ArgumentNullException("Options are required");
 }
Ejemplo n.º 15
0
 public CloudFoundryTokenValidator(CloudFoundryOptions options)
 {
     Options = options ?? throw new ArgumentNullException("options null");
 }
Ejemplo n.º 16
0
 public CloudFoundryTokenKeyResolver(CloudFoundryOptions options)
 {
     Options  = options ?? throw new ArgumentNullException("options null");
     Resolved = new Dictionary <string, SecurityKey>();
 }
 public CloudFoundryClientTokenResolver(CloudFoundryOptions options)
 {
     Options = options ?? throw new ArgumentNullException("options null");
 }