Esempio n. 1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="t"></param>
 /// <param name="databaseSettings"></param>
 /// <param name="hostingEnvironment"></param>
 /// <param name="linuxSettings"></param>
 public TokenController(TokenAuthOptions t, IOptions <DatabaseSettings> databaseSettings, IHostingEnvironment hostingEnvironment, IOptions <LinuxSettings> linuxSettings)
 {
     this._tokenOption   = t;
     _databaseSettings   = databaseSettings;
     _hostingEnvironment = hostingEnvironment;
     _linuxSettings      = linuxSettings;
 }
Esempio n. 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            tokenOptions = new TokenAuthOptions()
            {
                Audience           = TokenAudience,
                Issuer             = TokenIssuer,
                SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature)
            };


            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddSingleton <TokenAuthOptions>(tokenOptions);

            services.AddSingleton <DatabaseRepo>();

            services.AddSingleton <ApplicationContext>();

            services.AddMvc();
        }
Esempio n. 3
0
 public RefreshTokenManager(TokenAuthOptions tokenOptions, IAuthRequestValidators authRequestValidators, IRefreshTokenRepo refreshTokenRepo, IAdminLogger adminLogger)
 {
     _refreshTokenRepo      = refreshTokenRepo;
     _adminLogger           = adminLogger;
     _tokenOptions          = tokenOptions;
     _authRequestValidators = authRequestValidators;
 }
Esempio n. 4
0
        public virtual void ConfigureTokens(IServiceCollection services)
        {
            var contentRootPath = _hostingEnv.ContentRootPath;

            var           keyFile = new FileInfo(Path.Combine(contentRootPath, "key.json"));
            RSAParameters keyParams;

            if (keyFile.Exists)
            {
                keyParams = RSAKeyUtils.GetKeyParameters(Path.Combine(contentRootPath, "key.json"));
            }
            else
            {
                RSAKeyUtils.GenerateKeyAndSave(Path.Combine(contentRootPath, "key.json"));
                keyParams = RSAKeyUtils.GetKeyParameters(Path.Combine(contentRootPath, "key.json"));
            }


            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            _key          = new RsaSecurityKey(keyParams);
            _tokenOptions = new TokenAuthOptions
            {
                Audience           = TokenAudience,
                Issuer             = TokenIssuer,
                Key                = _key,
                SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.RsaSha256Signature)
            };
            // Save the token options into an instance so they're accessible to the
            // controller.
            services.AddSingleton(_tokenOptions);
            services.AddTransient <TokenService>();
        }
Esempio n. 5
0
        private void ConfigureAuthorization(IServiceCollection services, TimeSpan sessionTokenValidityTimeout, TimeSpan loginTokenValidityTimeout)
        {
            var keyBytes = Encoding.ASCII.GetBytes(Configuration["APIKey"]);

            key = new SymmetricSecurityKey(keyBytes);

            tokenOptions = new TokenAuthOptions
            {
                Audience                    = TokenAudience,
                Issuer                      = TokenIssuer,
                SigningCredentials          = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature),
                SessionTokenValidityTimeout = sessionTokenValidityTimeout,
                LoginTokenValidityTimeout   = loginTokenValidityTimeout
            };

            services.AddSingleton(tokenOptions);

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            });

            services.AddSingleton <IAuthorizationHandler, AuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, AuthorizationHandlerWithoutEntity>();

            services.AddSingleton <ClaimController>();
        }
Esempio n. 6
0
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCaching();

            services.AddSession(o =>
            {
                o.IdleTimeout = TimeSpan.FromSeconds(10);
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new GlobalExceptionFilter());
            });
            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            var appSettings = Configuration.Get <AppSettings>();

            key          = RSAKeyUtils.GetKey();
            tokenOptions = new TokenAuthOptions("ExampleAudience", "ExampleIssuer", key);
            services.AddInstance <TokenAuthOptions>(tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy(TokenAuthOptions.Scheme, new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(TokenAuthOptions.Scheme)
                               .RequireAuthenticatedUser()
                               .AddRequirements(new TokenAuthRequirement())
                               .Build());
            });

            DependencyInstaller.InjectDependencies(services, this.Configuration);
            _logger.LogInformation("Configuring Services");
        }
 public TokenController(TokenAuthOptions tokenOptions, ISignInManager<CustomUser> signInManager)
 {
     this.tokenOptions = tokenOptions;
     _signInManager = signInManager;
     //this.bearerOptions = options.Value;
     //this.signingCredentials = signingCredentials;
 }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Obtem os parâmetros para gerar o token com base na chave privada do certificado digital
            var rsaParameters = GetRSAParameters();

            //Criar uma chave para compor o token de autenticação
            _key = new RsaSecurityKey(rsaParameters);

            // Cria as informações que estaram no token
            _tokenOptions = new TokenAuthOptions
            {
                // Aplicação que está solicitando o token
                Audience = TokenAudience,

                // Aplicação que está gerando o token
                Issuer = TokenIssuer,

                // Credencias de entrada
                SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.RsaSha256Signature)
            };

            // Registro da classe TokenAuthOptions para injetar a depêndencia no controller que irá fazer a autenticação
            services.AddInstance <TokenAuthOptions>(_tokenOptions);


            // Adicionando o MVC e configuração Authorization Police e Authorize Filter
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });
        }
Esempio n. 9
0
 public LogonManager(IHttpContextAccessor contextAccessor, IMemoryCache memoryCache, IUnitOfWork unitOfWork, IOptions <TokenAuthOptions> tokenAuthOptions)
 {
     _contextAccessor  = contextAccessor;
     _memoryCache      = memoryCache;
     _unitOfWork       = unitOfWork;
     _tokenAuthOptions = tokenAuthOptions.Value;
 }
Esempio n. 10
0
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            RSACryptoServiceProvider myRSA     = new RSACryptoServiceProvider(2048);
            RSAParameters            publicKey = myRSA.ExportParameters(true);

            key = new RsaSecurityKey(publicKey);

            tokenOptions = new TokenAuthOptions
            {
                Audience           = "http://localhost:5000/",
                Issuer             = "http://localhost:5000/",
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            services.AddSingleton <TokenAuthOptions>(tokenOptions);

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });

            services.Configure <MvcJsonOptions>(options =>
            {
                if (_hostingEnv.IsDevelopment())
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                }

                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.Configure <MvcOptions>(options =>
            {
                options.CacheProfiles.Add("IndexPage",
                                          new CacheProfile
                {
                    Duration = 60 * 60 * 24
                });
            });

            services
            .AddIdentity <User, string>()
            .AddEF()
            .AddDefaultTokenProviders();

            services.AddCors();
            services.AddMvc();

            services.AddSingleton(_ => _configuration);

            services.AddEF();

            services.AddScoped <ITrainingService, TrainingService>();
            services.AddSingleton <IDateTimeService, DateTimeService>();
            services.AddScoped <ITrainingWordProvider, TrainingWordProvider>();
            services.AddScoped <ITrainingSessionFactory, TrainingSessionFactory>();
        }
Esempio n. 11
0
 public AuthenticationController(UserManager <ApplicationUser> userManager,
                                 SignInManager <ApplicationUser> signInManager,
                                 TokenAuthOptions tokenOptions)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _tokenOptions  = tokenOptions;
 }
Esempio n. 12
0
 public TokenController(IOptions <DatabaseSettings> dbSettings, IOptions <SecuritySettings> securitySettings, TokenAuthOptions tokenOptions)
 {
     _dbSettings        = dbSettings;
     _securitySettings  = securitySettings;
     _securityDbContext = new SecurityDbContext(_dbSettings.Value.ConnString);
     _securityUoW       = new SecurityUnitOfWork(_securityDbContext);
     this.tokenOptions  = tokenOptions;
 }
Esempio n. 13
0
 public TokenController(TokenAuthOptions tokenOptions,
                        IAuthenticationService authService,
                        ILogger <TokenController> logger)
 {
     _logger       = logger;
     _authService  = authService;
     _tokenOptions = tokenOptions;
 }
Esempio n. 14
0
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            var key = new RsaSecurityKey(keyParams);
            TokenAuthOptions tokenOptions = new TokenAuthOptions()
            {
                Audience           = ConfigurationManager.AppSettings["SiteUrl"],
                Issuer             = ConfigurationManager.AppSettings["SiteUrl"],
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            container.RegisterInstance <TokenAuthOptions>(tokenOptions);

            IMemoryCache memorycache = new MemoryCache(new MemoryCacheOptions());

            container.RegisterInstance <IMemoryCache>(memorycache);



            Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions op = new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions();
            op.AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active;
            op.TokenValidationParameters = new TokenValidationParameters
            {
                IssuerSigningKey         = key,
                ValidAudience            = tokenOptions.Audience,
                ValidateIssuerSigningKey = true,
                ValidateLifetime         = true,
                // For development purpose ClockSkew is set to zero to respect the token validity lifetime set in config.
                // Token expiration time = Issue time + expiration time in config + ClockSkew
                ClockSkew      = TimeSpan.Zero,
                ValidateIssuer = true,
                ValidIssuer    = tokenOptions.Issuer
            };

            container.RegisterInstance <Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions>(op);

            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterType <ISurveyQuestions, SurveyQuestionsAggregateRoot>();
            container.RegisterType <ISurveyRoot, SurveyRoot>();
            container.RegisterType <ICreationRepository, CreationRepository>();
            container.RegisterType <ISurveyRepository, SurveyRepository>();
            container.RegisterType <ISurveyContextAggregator, SurveyContextAggregator>();
            container.RegisterType <ISurveyResponse, SurveyResponse>();
            container.RegisterType <ISurveyResponseRepository, SurveyResponseRepository>();
            container.RegisterType <IAuthenticate, Authenticate>();
            container.RegisterType <IAuthorisationRepository, AuthorisationRepository>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
Esempio n. 15
0
 public TokenController(
     UserManager<ApplicationUser> userManager,
     SignInManager<ApplicationUser> signInManager,
     TokenAuthOptions tokenOptions)
 {
     _userManager = userManager;
     _signInManager = signInManager;
     _tokenOptions = tokenOptions;
 }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            key          = new SymmetricSecurityKey(Encoding.Unicode.GetBytes(Configuration["Token:Secret"]));
            tokenOptions = new TokenAuthOptions()
            {
                Audience           = Configuration["Token:Audience"],
                Issuer             = Configuration["Token:Issuer"],
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };

            services.AddSingleton <TokenAuthOptions>(tokenOptions);

            services.AddNodeServices();
            services.AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <BallotboxContext>(options =>
                                             options.UseNpgsql(Configuration["Data:BallotboxContextConnection"]));

            services.AddIdentity <BallotboxUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail             = true;
                config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
                config.Cookies.ApplicationCookie.Events    = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") &&
                            ctx.Response.StatusCode == (int)HttpStatusCode.OK)
                        {
                            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        return(Task.FromResult(0));
                    }
                };
            })
            .AddEntityFrameworkStores <BallotboxContext>()
            .AddDefaultTokenProviders();

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
            });

            services.AddTransient <BallotboxContextSeedData>();
            services.AddScoped <IBallotboxRepository, BallotboxRepository>();
        }
Esempio n. 17
0
 public AuthController(
     UserManager <BallotboxUser> userManager,
     SignInManager <BallotboxUser> signInManager,
     ILoggerFactory loggerFactory,
     TokenAuthOptions tokenOptions)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _logger        = loggerFactory.CreateLogger <AuthController>();
     _tokenOptions  = tokenOptions;
 }
Esempio n. 18
0
        //private readonly IConfiguration _configuration;

        //private readonly ILog _log;

        //private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public TokenController(TokenAuthOptions tokenOptions, KorisnikManager userManager, ISession session)
        {
            _tokenOptions = tokenOptions;
            _userManager  = userManager;

            _session = session;
            _minT    = tokenOptions.MinutaToken;
            _minRT   = tokenOptions.MinuntaRefreshToken;
            // _configuration = confuguration;
            //this.bearerOptions = options.Value;
            //this.signingCredentials = signingCredentials;
        }
Esempio n. 19
0
 public AuthController(TokenAuthOptions tokenOptions, UserManager <ApplicationUser> userManager,
                       SignInManager <ApplicationUser> signInManager, IEmailSender emailSender, IHostingEnvironment environment, IGolfConnectorDbContext db)
 {
     this.userManager   = userManager;
     this.signInManager = signInManager;
     this.tokenOptions  = tokenOptions;
     this.emailSender   = emailSender;
     this.environment   = environment;
     this.db            = db;
     // this.configuration = configuration;
     baseUrl = "http://localhost:7001/";
     // baseUrl = this.configuration.GetSection("Server:BaseUrl").Value;
 }
Esempio n. 20
0
        public RefreshTokens(BusinessDbContext context, ISmsSender smsSender,
                             ILogger <RefreshTokens> logger,
                             ITokenMemoryCache memoryCache,
                             TokenAuthOptions tokenOptions,
                             TokenService tokenService, IHostingEnvironment hostingEnvironment)
        {
            _context     = context;
            _smsSender   = smsSender;
            _logger      = logger;
            _memoryCache = memoryCache;

            _tokenService       = tokenService;
            _hostingEnvironment = hostingEnvironment;
        }
Esempio n. 21
0
        public Startup(IHostingEnvironment env)
        {
            _key          = Infra.Security.GetKey();
            _tokenOptions = Infra.TokenAuth.GetToken(_key);


            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();
        }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure auth

            // Replace this with some sort of loading from config / file.
            RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            key          = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience           = TokenAudience,
                Issuer             = TokenIssuer,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            // Save the token options into an instance so they're accessible to the
            // controller.
            services.AddSingleton <TokenAuthOptions>(tokenOptions);

            // Enable the use of an [Authorize("Bearer")] attribute on methods and
            // classes to protect.
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            // Add framework services.
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <ApplicationDbContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity <Tunee, TuneeRole>(options =>
            {
                options.Cookies.ApplicationCookie.AutomaticChallenge = false;
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 5; // TODO: Store in config somewhere.
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext, Guid>()
            .AddDefaultTokenProviders();
            services.AddMvc();
        }
Esempio n. 23
0
        public async Task <ActionResult> Login([FromBody] LoginViewModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(Json(model));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(Ok(new
                {
                    authenticated = false,
                    message = "You are unautorized to access this site."
                }));
            }
            if (!user.EmailConfirmed)
            {
                return(Ok(new
                {
                    authenticated = false,
                    message = "User is registered and can login after activation."
                }));
            }

            var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false);

            var roles = await _userManager.GetRolesAsync(user);

            var token = TokenAuthOptions.GenerateToken(user.UserName);

            if (result.Succeeded)
            {
                return(Ok(new
                {
                    authenticated = true,
                    token = token,
                    user = user,
                    message = "Welcome to the Identity"
                }));
            }
            if (result.IsLockedOut)
            {
                return(BadRequest("User account locked out."));
            }
            return(BadRequest("Something wen't wrong."));
        }
Esempio n. 24
0
        public void Init()
        {
            _signInManager         = new Mock <ISignInManager>();
            _userManager           = new Mock <IUserManager>();
            _refreshTokenManager   = new Mock <IRefreshTokenManager>();
            _tokenHelper           = new Mock <ITokenHelper>();
            _orgHelper             = new Mock <IOrgHelper>();
            _appInstanceManager    = new Mock <IAppInstanceManager>();
            _authRequestValidators = new Mock <IAuthRequestValidators>();

            var tokenOptions = new TokenAuthOptions()
            {
                AccessExpiration  = TimeSpan.FromMinutes(90),
                RefreshExpiration = TimeSpan.FromDays(90),
            };

            _authTokenManager = new AuthTokenManager(new Mock <IAppInstanceRepo>().Object, _refreshTokenManager.Object, _authRequestValidators.Object, _orgHelper.Object, _tokenHelper.Object, _appInstanceManager.Object, new Mock <IAdminLogger>().Object, _signInManager.Object, _userManager.Object);

            _appInstanceManager.Setup(ais => ais.UpdateLastLoginAsync(It.IsAny <string>(), It.IsAny <AuthRequest>())).ReturnsAsync(InvokeResult <AppInstance> .Create(new AppInstance("rowid", "userid")));
            _appInstanceManager.Setup(ais => ais.UpdateLastAccessTokenRefreshAsync(It.IsAny <string>(), It.IsAny <AuthRequest>())).ReturnsAsync(InvokeResult <AppInstance> .Create(new AppInstance("rowid", "userid")));

            _signInManager.Setup(sim => sim.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>())).Returns(Task.FromResult(InvokeResult.Success));
            _userManager.Setup(usm => usm.FindByIdAsync(It.IsAny <string>())).Returns(Task.FromResult(new AppUser()
            {
                Id = Guid.NewGuid().ToId()
            }));
            _userManager.Setup(usm => usm.FindByNameAsync(It.IsAny <string>())).Returns(Task.FromResult(new AppUser()
            {
                Id = Guid.NewGuid().ToId()
            }));
            _orgHelper.Setup(ohlp => ohlp.SetUserOrgAsync(It.IsAny <AuthRequest>(), It.IsAny <AppUser>())).Returns(Task.FromResult(InvokeResult.Success));
            _refreshTokenManager.Setup(rtm => rtm.GenerateRefreshTokenAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(Task <RefreshToken> .FromResult(InvokeResult <RefreshToken> .Create(new RefreshToken("XXXX"))));
            _authRequestValidators.Setup(arv => arv.ValidateAuthRequest(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _authRequestValidators.Setup(arv => arv.ValidateAccessTokenGrant(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _authRequestValidators.Setup(arv => arv.ValidateRefreshTokenGrant(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _tokenHelper.Setup(tlp => tlp.GenerateAuthResponse(It.IsAny <AppUser>(), It.IsAny <AuthRequest>(), It.IsAny <InvokeResult <RefreshToken> >())).Returns(new InvokeResult <AuthResponse>()
            {
                Result = new AuthResponse()
                {
                    AccessToken           = "ACC",
                    AccessTokenExpiresUTC = DateTime.Now.AddMinutes(30).ToJSONString(),
                }
            });
        }
Esempio n. 25
0
        private async Task <string> GenerateTokenAsync(User user)
        {
            var            handler  = new JwtSecurityTokenHandler();
            ClaimsIdentity identity = new ClaimsIdentity(
                GetTokenClaims(user).Union(await _userManager.GetClaimsAsync(user))
                );

            var expiresIn     = DateTime.Now + TimeSpan.FromMinutes(TokenAuthOptions.LIFETIME);
            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = TokenAuthOptions.ISSUER,
                Audience           = TokenAuthOptions.AUDIENCE,
                SigningCredentials = new SigningCredentials(TokenAuthOptions.GetKey(), SecurityAlgorithms.HmacSha256),
                Subject            = identity,
                Expires            = expiresIn
            });

            return(handler.WriteToken(securityToken));
        }
Esempio n. 26
0
        public static void RegisterBearerPolicy(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });

            TokenAuthOptions tokenOptions = new TokenAuthOptions
            {
                Audience           = configuration["Jwt:Audience"],
                Issuer             = configuration["Jwt:Issuer"],
                LifeSpan           = TimeSpan.FromMinutes(Convert.ToDouble(configuration["Jwt:TokenLifespan"])),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])),
                    SecurityAlgorithms.HmacSha512Signature)
            };

            services.AddSingleton(tokenOptions);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience,
                    IssuerSigningKey = tokenOptions.SigningCredentials.Key,
                    ClockSkew        = tokenOptions.LifeSpan
                };
            });
        }
Esempio n. 27
0
        public void ConfigureServices(IServiceCollection services)
        {
            tokenOptions = new TokenAuthOptions()
            {
                Audience   = TokenAudience,
                Issuer     = TokenIssuer,
                SigningKey = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256)
            };

            services.AddDbContext <AppDBContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddSingleton <IUserRepository, UserRepository>();
            services.AddSingleton <IQuoteRepository, QuoteRepository>();
            services.AddSingleton <IPreferenceRepository, PreferenceRepository>();
            services.AddSingleton <IQuestionRepository, QuestionRepository>();
            services.AddSingleton <IPhotoRepository, PhotoRepository>();
            services.AddSingleton <IDetailRepository, DetailRepository>();
            services.AddSingleton <IFeedbackRepository, FeedbackRepository>();
            services.AddSingleton <IConversationRepository, ConversationRepository>();
            services.AddSingleton <ISearchRepository, SearchRepository>();
            services.AddSingleton <INotificationRepository, NotificationRepository>();
            services.AddSingleton <IMatchQuestionRepository, MatchQuestionRepository>();

            // TODO Cors fo testing
            services.AddCors();

            services.AddMvc();

            services.AddSingleton(tokenOptions);

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });
        }
Esempio n. 28
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            _key = new StaticKeyGen().Key;
            _tokenAuthOptions = new TokenAuthOptions()
            {
                Audience           = "http://localhost:5000",
                Issuer             = "issurer",
                SigningCredentials = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256)
            };

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }
Esempio n. 29
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            #region Token Config
            // *** CHANGE THIS FOR PRODUCTION USE ***
            // Here, we're generating a random key to sign tokens - obviously this means
            // that each time the app is started the key will change, and multiple servers
            // all have different keys. This should be changed to load a key from a file
            // securely delivered to your application, controlled by configuration.
            //
            // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from
            // a JSON file.
            var keyParams = RSAKeyUtils.GetRandomKey(); //TODO secure storage

            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            key          = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions
            {
                Audience           = Configuration["TokenAudience"],
                Issuer             = Configuration["TokenIssuser"],
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            // Save the token options into an instance so they're accessible to the
            // controller.
            services.AddSingleton(tokenOptions);

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               //     .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            //   services.Configure<Settings>(Configuration.GetSection("App"));

            #endregion

            services.AddSignalR(options =>
            {
                options.Hubs.EnableDetailedErrors = true;
            });

            #region Services

            services.AddScoped <IOAuthHandler, OAuthHandler>();
            services.AddScoped <IMembershipService, MembershipService>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IEncryptionService, EncryptionService>();
            services.AddScoped <IApiErrorHandler, ApiErrorHandler>();
            services.AddScoped <IEventRepository, EventRepository>();
            services.AddScoped <ITeamRepository, TeamRepository>();
            services.AddTransient <IConnectionManager, ConnectionManager>();
            services.AddScoped <IQuestionRepository, QuestionRepository>();


            #endregion

            services.AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <RscContext>();

            services.AddDbContext <RscContext>(options =>
                                               options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddSwaggerGen();


            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();
            services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });

            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddSignalR();

            services.AddMvc()
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.ContractResolver           = new CamelCasePropertyNamesContractResolver();
                opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            }); services.AddMvc();
        }
Esempio n. 30
0
 public TokenController(IAccountService accountService, TokenAuthOptions tokenOptions)
 {
     this.tokenOptions = tokenOptions;
     _accountService   = accountService;
 }
Esempio n. 31
0
 public TokenService(TokenAuthOptions tokenOptions, IAuthenticationProvider authenticationProvider)
 {
     _tokenOptions           = tokenOptions;
     _authenticationProvider = authenticationProvider;
 }
 public TokenController(TokenAuthOptions tokenOptions)
 {
     this.tokenOptions = tokenOptions;
     //this.bearerOptions = options.Value;
     //this.signingCredentials = signingCredentials;
 }
 public TokenController(TokenAuthOptions tokenOptions)
 {
     this.tokenOptions = tokenOptions;
     //this.bearerOptions = options.Value;
     //this.signingCredentials = signingCredentials;
 }