Example #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            var openidJsonWebKey   = ExtractOpenIDJsonWebKey();
            var rsaParameters      = new RSAParameters
            {
                Modulus  = openidJsonWebKey.Content[RSAFields.Modulus].Base64DecodeBytes(),
                Exponent = openidJsonWebKey.Content[RSAFields.Exponent].Base64DecodeBytes()
            };
            var oauthRsaSecurityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsaParameters);

            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr")
                };
                options.DefaultRequestCulture = new RequestCulture("en");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });
            services.AddLogging();
            services.AddMvc(o =>
            {
                o.EnableEndpointRouting = false;
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization()
            .AddNewtonsoftJson(o => { });
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = UMAConstants.SignInScheme;
                opts.DefaultSignInScheme       = UMAConstants.SignInScheme;
                opts.DefaultChallengeScheme    = UMAConstants.ChallengeAuthenticationScheme;
            }).AddCookie(UMAConstants.SignInScheme)
            .AddOpenIdConnect(UMAConstants.ChallengeAuthenticationScheme, options =>
            {
                options.ClientId     = "umaClient";
                options.ClientSecret = "umaClientSecret";
                options.Authority    = "https://localhost:60000";
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.SaveTokens   = true;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = oauthRsaSecurityKey
                };
            });
            services.AddAuthorization(p => p.AddDefaultOAUTHAuthorizationPolicy());
            services.AddSIDUma(options =>
            {
                options.OpenIdJsonWebKeySignature = openidJsonWebKey;
            }).AddSIDUmaEF(opt =>
            {
                opt.UseSqlServer("Data Source=DESKTOP-T4INEAM\\SQLEXPRESS;Initial Catalog=Uma;Integrated Security=True", o => o.MigrationsAssembly(migrationsAssembly));
            });
        }
        private void RetrieveMetadata()
        {
            if (_syncAfter >= DateTimeOffset.UtcNow)
            {
                return;
            }

            _synclock.EnterWriteLock();
            try
            {
                var result = AsyncHelper.RunSync(() => _configurationManager.GetConfigurationAsync(CancellationToken.None));

                if (result.JsonWebKeySet == null)
                {
                    _logger.WriteError("Discovery document has no configured signing key. aborting.");
                    throw new InvalidOperationException("Discovery document has no configured signing key. aborting.");
                }

                var keys = new List <Microsoft.IdentityModel.Tokens.SecurityKey>();
                foreach (var key in result.JsonWebKeySet.Keys)
                {
                    var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(new RSAParameters
                    {
                        Exponent = Microsoft.IdentityModel.Tokens.Base64UrlEncoder.DecodeBytes(key.E),
                        Modulus  = Microsoft.IdentityModel.Tokens.Base64UrlEncoder.DecodeBytes(key.N)
                    })
                    {
                        KeyId = key.Kid //key.KeyId is null (should be cert thumbprint)! Kid is x5t!
                    };

                    keys.Add(securityKey);
                }

                _issuer    = result.Issuer;
                _keys      = keys;
                _syncAfter = DateTimeOffset.UtcNow + _automaticRefreshInterval;
            }
            catch (Exception ex)
            {
                _logger.WriteError("Error contacting discovery endpoint: " + ex.ToString());
                throw;
            }
            finally
            {
                _synclock.ExitWriteLock();
            }
        }
Example #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            var openidJsonWebKey = ExtractOpenIDJsonWebKey();
            var rsaParameters    = new RSAParameters
            {
                Modulus  = openidJsonWebKey.Content[RSAFields.Modulus].Base64DecodeBytes(),
                Exponent = openidJsonWebKey.Content[RSAFields.Exponent].Base64DecodeBytes()
            };
            var oauthRsaSecurityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsaParameters);
            var oauthJsonWebKey     = ExtractOAuthJsonWebKey();

            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr")
                };
                options.DefaultRequestCulture = new RequestCulture("en");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });
            services.AddLogging();
            services.AddMvc(o =>
            {
                o.EnableEndpointRouting = false;
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization()
            .AddNewtonsoftJson(o => { });
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = UMAConstants.SignInScheme;
                opts.DefaultSignInScheme       = UMAConstants.SignInScheme;
                opts.DefaultChallengeScheme    = UMAConstants.ChallengeAuthenticationScheme;
            }).AddCookie(UMAConstants.SignInScheme)
            .AddOpenIdConnect(UMAConstants.ChallengeAuthenticationScheme, options =>
            {
                options.ClientId     = "umaClient";
                options.ClientSecret = "umaClientSecret";
                options.Authority    = "https://localhost:60000";
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.SaveTokens   = true;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = oauthRsaSecurityKey
                };
            });
            services.AddAuthorization(p => p.AddDefaultOAUTHAuthorizationPolicy());
            services.AddSIDUma(options =>
            {
                options.OpenIdJsonWebKeySignature = openidJsonWebKey;
            })
            .AddUmaResources(DefaultConfiguration.Resources)
            .AddUMARequests(DefaultConfiguration.PendingRequests)
            .AddClients(DefaultConfiguration.DefaultClients)
            .AddScopes(DefaultConfiguration.DefaultScopes)
            .AddJsonWebKeys(new List <JsonWebKey> {
                oauthJsonWebKey
            });
        }
Example #4
0
        public void ConfigureJwtAuthorizationFlow(string clientId, string userId, string oauthBasePath, string privateKeyFilename, int expiresInHours)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Expires = DateTime.UtcNow.AddHours(expiresInHours),
            };

            descriptor.Subject = new ClaimsIdentity();
            descriptor.Subject.AddClaim(new Claim("scope", "signature"));
            descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath));
            descriptor.Subject.AddClaim(new Claim("iss", clientId));

            if (userId != null)
            {
                descriptor.Subject.AddClaim(new Claim("sub", userId));
            }

            if (privateKeyFilename != null)
            {
                string pemKey = File.ReadAllText(privateKeyFilename);
                var    rsa    = CreateRSAKeyFromPem(pemKey);
                Microsoft.IdentityModel.Tokens.RsaSecurityKey rsaKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsa);
                descriptor.SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature);
            }

            var    token    = handler.CreateToken(descriptor);
            string jwtToken = handler.WriteToken(token);

            Uri baseUrl = this.RestClient.BaseUrl;

            this.RestClient.BaseUrl = new Uri(string.Format("https://{0}", oauthBasePath));

            string path        = "oauth/token";
            string contentType = "application/x-www-form-urlencoded";

            Dictionary <string, string> formParams = new Dictionary <string, string>();

            formParams.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
            formParams.Add("assertion", jwtToken);

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            Dictionary <string, string> headerParams = new Dictionary <string, string>();

            headerParams.Add("Content-Type", "application/x-www-form-urlencoded");

            Dictionary <string, FileParameter> fileParams = new Dictionary <string, FileParameter>();
            Dictionary <string, string>        pathParams = new Dictionary <string, string>();

            object postBody = null;

            try
            {
                var           response  = CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
                TokenResponse tokenInfo = JsonConvert.DeserializeObject <TokenResponse>(((RestResponse)response).Content);

                var config = Configuration.Default;
                config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token));
            }
            catch (Exception ex)
            {
            }

            this.RestClient.BaseUrl = baseUrl;
        }