Exemple #1
0
        public void CommonTokenRequestParamsHandlesScopes()
        {
            var opts = new AuthServerOptions {
                AdditionalTokenScopes = "onescope", RequiredScopes = new string[] { "twoscope" }
            };
            var tEx = new TokenExchanger(opts);

            var parameters = tEx.CommonTokenRequestParams();

            Assert.Equal("openid onescope twoscope", parameters.First(i => i.Key == CloudFoundryDefaults.ParamsScope).Value);
        }
Exemple #2
0
        public async Task ExchangeAuthCodeForClaimsIdentity_ExchangesCodeForIdentity()
        {
            var options = new AuthServerOptions()
            {
                AuthorizationUrl = "http://localhost/tokenUrl"
            };
            var exchanger = new TokenExchanger(options, GetMockHttpClient());

            var identity = await exchanger.ExchangeAuthCodeForClaimsIdentity("goodCode");

            Assert.IsType <ClaimsIdentity>(identity);
        }
Exemple #3
0
        public async Task ExchangeAuthCodeForClaimsIdentity_ReturnsNullOnFailure()
        {
            var options = new AuthServerOptions()
            {
                AuthorizationUrl = "http://localhost/tokenUrl"
            };
            var httpClient = new object(); // TODO: replace with mock that does stuff
            var exchanger  = new TokenExchanger(options, GetMockHttpClient());

            var identity = await exchanger.ExchangeAuthCodeForClaimsIdentity("badCode");

            Assert.Null(identity);
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
                //for TESTING PURPOSES - CHANGE TO SSL(true value)
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthServerOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = AuthServerOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthServerOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });
            // enable CORS for template-engine front-end
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder => builder.WithOrigins(Configuration.GetValue <string>("FrontEndOrigin"),
                                                                 Configuration.GetValue <string>("PluginOrigin")).AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials());
            });
            // get scaffold settings model from appsettings.json
            services.Configure <UserDatabaseSettingsModel>(
                Configuration.GetSection(nameof(UserDatabaseSettingsModel)));

            //register settigs class to be a singleton service
            services.AddSingleton <IBaseSettingsModels>(sp =>
                                                        sp.GetRequiredService <IOptions <UserDatabaseSettingsModel> >().Value);

            //register scaffold service as singleton service
            // as it uses MongoDb client and it's good practice that multiple
            // clients should not be created
            services.AddSingleton <ScaffoldService>();

            services.AddSingleton <UserService>();

            services.AddSingleton <ProjectsService>();

            services.AddSingleton <ResumeService>();

            //register webScrapper to be a singleton service
            services.AddHostedService <ScaffoldService>().AddSingleton <IWebScrapper, CompanySiteWebScrapper>();

            services.AddControllers().AddNewtonsoftJson();
            _ = services.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo {
                Title = "engine_plugin_backend", Version = "v1"
            }));
        }
Exemple #5
0
        public void ClientCredentialsTokenRequestParameters_ReturnsCorrectly()
        {
            var opts = new AuthServerOptions {
                ClientId = "clientId", ClientSecret = "clientSecret", CallbackUrl = "redirect_uri"
            };
            var tEx = new TokenExchanger(opts);

            var parameters = tEx.ClientCredentialsTokenRequestParameters();

            Assert.NotNull(parameters);
            Assert.Equal(opts.ClientId, parameters.First(i => i.Key == "client_id").Value);
            Assert.Equal(opts.ClientSecret, parameters.First(i => i.Key == "client_secret").Value);
            Assert.Equal(OpenIdConnectGrantTypes.ClientCredentials, parameters.First(i => i.Key == "grant_type").Value);
        }
Exemple #6
0
        public void GetTokenRequestMessage_ReturnsCorrectly()
        {
            var opts = new AuthServerOptions {
                ClientId = "clientId", ClientSecret = "clientSecret"
            };
            var tEx = new TokenExchanger(opts);

            var message = tEx.GetTokenRequestMessage(new List <KeyValuePair <string, string> >(), "redirectUri");

            Assert.NotNull(message);
            var content = message.Content as FormUrlEncodedContent;

            Assert.NotNull(content);
            Assert.Equal(HttpMethod.Post, message.Method);

            Assert.Contains(new MediaTypeWithQualityHeaderValue("application/json"), message.Headers.Accept);
        }
        public void AuthCodeTokenRequestParameters_ReturnsCorrectly()
        {
            // arrange
            var opts = new AuthServerOptions {
                ClientId = "clientId", ClientSecret = "clientSecret", CallbackUrl = "redirect_uri"
            };
            var tEx = new TokenExchanger(opts);

            // act
            var parameters = tEx.AuthCodeTokenRequestParameters("authcode");

            // assert
            Assert.NotNull(parameters);
            Assert.Equal(opts.ClientId, parameters.First(i => i.Key == "client_id").Value);
            Assert.Equal(opts.ClientSecret, parameters.First(i => i.Key == "client_secret").Value);
            Assert.Equal("redirect_uri", parameters.First(i => i.Key == "redirect_uri").Value);
            Assert.Equal("authcode", parameters.First(i => i.Key == "code").Value);
            Assert.Equal(OpenIdConnectGrantTypes.AuthorizationCode, parameters.First(i => i.Key == "grant_type").Value);
        }
Exemple #8
0
        public void ConfigureOauth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings["issuer"];
            var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

            AuthServerOptions.OabOpts = new OAuthBearerAuthenticationOptions();
            var serverOpts = new AuthServerOptions(issuer);


            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                AllowedAudiences   = new[] { "Any" },

                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

            app.UseOAuthAuthorizationServer(serverOpts.OauthOpts);
        }
Exemple #9
0
        public IActionResult SignInUser([FromBody] UserModel userModel)
        {
            var userIdentity = _userService.GetIdentity(userModel.Email, userModel.Password);

            if (userIdentity == null)
            {
                return(BadRequest(new { errorText = "Invalid email or password" }));
            }
            var timeNow = DateTime.UtcNow;
            var jwt     = new JwtSecurityToken(
                issuer: AuthServerOptions.ISSUER,
                audience: AuthServerOptions.AUDIENCE,
                claims: userIdentity.Claims, notBefore: timeNow,
                expires: timeNow.Add(TimeSpan.FromMinutes(AuthServerOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthServerOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new  {
                access_token = encodedJwt,
                username     = userIdentity.Name,
            };

            return(Json(response));
        }
 public DefaultTokenGenerator(ISecurityKeyProvider certProvider, ITokenClaimBuilder claimGenerator, AuthServerOptions options)
 {
     AuthServerOptions    = options;
     _securityKeyProvider = certProvider;
     _claimGenerator      = claimGenerator;
 }
Exemple #11
0
        private static void CheckOptions(IServiceCollection services, AuthServerOptions options)
        {
            // AuthServer
            if (options.AuthServerFactory != null)
            {
                services.AddSingleton(options.AuthServerFactory);
            }
            else
            {
                // use default
                services.AddSingleton <IAuthServer, DefaultAuthServer>();
            }

            // ClientValidator
            if (options.ClientValidatorFactory != null)
            {
                services.AddSingleton(options.ClientValidatorFactory);
            }
            else
            {
                // use default
                services.AddSingleton <IClientValidator, DefaultClientValidator>();
            }

            // ResourceOwnerValidator
            if (options.ResourceOwnerValidatorFactory != null)
            {
                services.AddSingleton(options.ResourceOwnerValidatorFactory);
            }
            else
            {
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.ResourceOwnerValidatorFactory)}");
            }

            // TokenGenerator
            if (options.TokenGeneratorFactory != null)
            {
                services.AddSingleton(options.TokenGeneratorFactory);
            }
            else
            {
                // use default
                services.AddSingleton <ITokenGenerator, DefaultTokenGenerator>();
            }

            // AuthCodeStore
            if (options.AuthCodeStoreFactory != null)
            {
                services.AddSingleton(options.AuthCodeStoreFactory);
            }
            else
            {
                // use default
                services.AddSingleton <IAuthCodeStore, DefaultAuthCodeStore>();
            }

            // AuthCodeGenerator
            if (options.AuthCodeGeneratorFactory != null)
            {
                services.AddSingleton(options.AuthCodeGeneratorFactory);
            }
            else
            {
                // use default
                services.AddSingleton <IAuthCodeGenerator, DefaultAuthCodeGenerator>();
            }

            // PkceValidator
            if (options.PkceValidatorFactory != null)
            {
                services.AddSingleton(options.PkceValidatorFactory);
            }
            else
            {
                // use default
                services.AddSingleton <IPkceValidator, DefaultPkceValidator>();
            }

            // ClaimGenerator
            if (options.TokenClaimBuilderFactory != null)
            {
                services.AddSingleton(options.TokenClaimBuilderFactory);
            }
            else
            {
                // no default, must provde
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.TokenClaimBuilderFactory)}");
            }

            // SecurityKeyProvider
            if (options.SecurityKeyProviderFactory != null)
            {
                services.AddSingleton(options.SecurityKeyProviderFactory);
            }
            else
            {
                // no default, must provde
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.SecurityKeyProviderFactory)}");
            }

            // ClientStore
            if (options.ClientStoreFactory != null)
            {
                services.AddSingleton(options.ClientStoreFactory);
            }
            else
            {
                // no default, must provde
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.ClientStoreFactory)}");
            }

            // TokenStore
            if (options.TokenStoreFactory != null)
            {
                services.AddSingleton(options.TokenStoreFactory);
            }
            else
            {
                // no default, must provde
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.TokenStoreFactory)}");
            }

            // TokenStore
            if (options.StateStoreFactory != null)
            {
                services.AddSingleton(options.StateStoreFactory);
            }
            else
            {
                // no default, must provde
                throw new ArgumentNullException($"{nameof(options)}.{nameof(options.StateStoreFactory)}");
            }
        }
Exemple #12
0
        public static IServiceCollection AddOAuth2AuthServer(this IServiceCollection services, Action <AuthServerOptions> configOptions, AuthServerOptions options = null)
        {
            options = options ?? new AuthServerOptions();

            configOptions(options);

            services.AddSingleton(options);

            CheckOptions(services, options);

            return(services);
        }