Exemple #1
0
        public virtual void SetUp()
        {
            cert    = new CertificateX509();
            key     = new PrivateKeyManager();
            options = new JWTOptions();
            claims  = new PrivateClaims();
            du      = new DateUtil();
            jwt     = new JWTCreator();


            cert.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256_cert.crt");
            options.SetCertificate(cert);


            key.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256d_key.pem");
            options.SetPrivateKey(key);
            //
            // carga de privateClaim (es parte del Payload)
            claims.setClaim("GeneXus", "Viglia");


            // Carga de Registered Claims
            options.AddRegisteredClaim("iss", "Martin");
            options.AddRegisteredClaim("sub", "Martin1");
            options.AddRegisteredClaim("aud", "martivigliadoocebbooyo.docebosaas.com");
            options.AddCustomTimeValidationClaim("iat", du.GetCurrentDate(), "20");
            options.AddCustomTimeValidationClaim("exp", du.CurrentPlusSeconds(3600), "20");
            options.AddPublicClaim("client_id", "Martin");

            token    = jwt.DoCreate("RS256", claims, options);
            expected = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
        }
Exemple #2
0
        public virtual void SetUp()
        {
            options1 = new JWTOptions();
            options2 = new JWTOptions();
            jwt      = new JWTCreator();
            claims   = new PrivateClaims();
            claims.setClaim("hola1", "hola1");
            path_RSA_sha256_1024 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha256_1024");

            String            pathKey  = Path.Combine(path_RSA_sha256_1024, "sha256d_key.pem");
            String            pathCert = Path.Combine(path_RSA_sha256_1024, "sha256_cert.crt");
            PrivateKeyManager key      = new PrivateKeyManager();
            CertificateX509   cert     = new CertificateX509();

            key.Load(pathKey);
            cert.Load(pathCert);

            options1.SetCertificate(cert);
            options1.SetPrivateKey(key);
            options1.AddRegisteredClaim("iss", "GXSA");
            options1.AddRegisteredClaim("sub", "subject1");
            options1.AddRegisteredClaim("aud", "audience1");

            options2.AddRegisteredClaim("iss", "GXSA");
            options2.AddRegisteredClaim("sub", "subject1");
            options2.AddRegisteredClaim("aud", "audience1");
            options2.SetCertificate(cert);

            token = jwt.DoCreate("RS256", claims, options1);
        }
        public virtual void SetUp()
        {
            du           = new DateUtil();
            guid         = new GUID();
            keyGenerator = new SymmetricKeyGenerator();
            jwt          = new JWTCreator();
            options      = new JWTOptions();
            claims       = new PrivateClaims();

            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");

            options.AddRegisteredClaim("jti", guid.Generate());

            options.AddCustomTimeValidationClaim("exp", du.CurrentPlusSeconds(100), "20");
            options.AddCustomTimeValidationClaim("iat", du.GetCurrentDate(), "20");
            options.AddCustomTimeValidationClaim("nbf", du.GetCurrentDate(), "20");

            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");

            path_RSA_sha256_1024 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha256_1024");
            path_RSA_sha256_2048 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha256_2048");
            path_RSA_sha512_2048 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha512_2048");
            path_EC = Path.Combine(BASE_PATH, "dummycerts", "JWT_ECDSA", "prime_test");

            alias    = "1";
            password = "******";
        }
        public virtual void SetUp()
        {
            jwt     = new JWTCreator();
            options = new JWTOptions();
            keyGen  = new SymmetricKeyGenerator();
            claims  = new PrivateClaims();
            rList   = new RevocationList();



            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");
            ID = "0696bb20-6223-4a1c-9ebf-e15c74387b9c, 0696bb20-6223-4a1c-9ebf-e15c74387b9c";            //&guid.Generate()
            options.AddRegisteredClaim("jti", ID);
            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");

            String hexaKey = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options.SetSecret(hexaKey);
            options.AddRevocationList(rList);

            token = jwt.DoCreate("HS256", claims, options);
        }
Exemple #5
0
        public (bool, string, DateTime?) GetTokenForUser(string login, string password)
        {
//            var request = new RestRequest(Method.GET);

//            var client = new RestClient("http://gpncb.skillunion.ru/auth");
//            client.Authenticator = new NtlmAuthenticator($"skillunion\\{login}", password);
//            client.Timeout = -1;

//            client.Execute(request);

//            var response = await client.ExecuteAsync(request).ConfigureAwait(false);
//            var ret = JsonSerializer.Deserialize<int>(response.Content);
//            if (ret == 1) ; // OK


            var user = _users.FirstOrDefault(u => u.Login.Equals(login, StringComparison.InvariantCultureIgnoreCase));

            if (user == null || !password.Equals(user.Password))
            {
                return(false, null, null);
            }

            (user.Token, user.Expires) = JWTOptions.Token(user.Login);

            return(true, user.Token, user.Expires);
        }
Exemple #6
0
        public JWTAndRefreshToken Login(string login, string password)
        {
            var person = _personRepository.GetPersonByLoginAndPassword(login, password);

            if (person != null)
            {
                ClaimsIdentity identity = GetIdentity(login, password);
                if (identity == null)
                {
                    jwt = null;
                    return(null);
                }
                DateTime timeNow = DateTime.UtcNow;
                jwt = new JwtSecurityToken(
                    issuer: JWTOptions.ISSUER,
                    audience: JWTOptions.AUDIENCE,
                    claims: identity.Claims,
                    notBefore: timeNow,
                    expires: timeNow.AddMinutes(1),
                    signingCredentials: new SigningCredentials(
                        JWTOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

                string accessToken  = new JwtSecurityTokenHandler().WriteToken(jwt);
                string refreshToken = Guid.NewGuid().ToString();
                person.RefreshToken = refreshToken;
                _personRepository.Update(person);

                JWTAndRefreshToken JWTAndRefreshToken = new JWTAndRefreshToken {
                    AccessToken = accessToken, RefreshToken = refreshToken
                };
                return(JWTAndRefreshToken);
            }
            return(null);
        }
        public virtual void SetUp()
        {
            jwt     = new JWTCreator();
            options = new JWTOptions();

            keyGen       = new SymmetricKeyGenerator();
            claimslevel1 = new PrivateClaims();
            claimslevel2 = new PrivateClaims();
            claimslevel3 = new PrivateClaims();


            hexaKey = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options.AddRegisteredClaim("aud", "jitsi");
            options.AddRegisteredClaim("iss", "my_client");
            options.AddRegisteredClaim("sub", "meet.jit.si");


            claimslevel1.setClaim("room", "*");

            claimslevel1.setClaim("context", claimslevel2);

            claimslevel2.setClaim("user", claimslevel3);
            claimslevel3.setClaim("avatar", "https:/gravatar.com/avatar/abc123");
            claimslevel3.setClaim("name", "John Doe");
            claimslevel3.setClaim("email", "*****@*****.**");
            claimslevel3.setClaim("id", "abcd:a1b2c3-d4e5f6-0abc1-23de-abcdef01fedcba");
            claimslevel2.setClaim("group", "a123-123-456-789");

            options.SetSecret(hexaKey);
            token = jwt.DoCreate("HS256", claimslevel1, options);
        }
        public virtual void SetUp()
        {
            jwt     = new JWTCreator();
            options = new JWTOptions();
            du      = new DateUtil();
            keyGen  = new SymmetricKeyGenerator();
            claims  = new PrivateClaims();

            currentDate = du.GetCurrentDate();
            hexaKey     = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options.AddRegisteredClaim("aud", "jitsi");
            options.AddRegisteredClaim("iss", "my_client");
            options.AddRegisteredClaim("sub", "meet.jit.si");
            string expiration = du.CurrentPlusSeconds(200);

            options.AddCustomTimeValidationClaim("exp", expiration, "20");

            claims.setClaim("hola", "hola");

            options.AddHeaderParameter("cty", "twilio-fpa;v=1");
            options.SetSecret(hexaKey);

            token = jwt.DoCreate("HS256", claims, options);
        }
Exemple #9
0
        public async Task <string> GenerateEncodedToken(string email, ClaimsIdentity identity)
        {
            var now = DateTime.UtcNow;

            var user = await _userManager.FindByEmailAsync(email);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, await JWTOptions.NonceGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, UnixEpochDateGenerator.ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Rol),
                identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Id)
            };
            // создаем JWT-токен
            var jwt = new JwtSecurityToken(
                issuer: JWTOptions.ISSUER,
                audience: JWTOptions.AUDIENCE,
                notBefore: now,
                claims: claims,
                expires: now.Add(TimeSpan.FromMinutes(JWTOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(JWTOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
Exemple #10
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var JWTOptions = new JWTOptions();

            configuration.GetSection(JWTOptions.SectionName).Bind(JWTOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = JWTOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = JWTOptions.Audience,

                    ValidateLifetime = true,

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = JWTOptions.GetSymmetricSecurityKey()
                };
            });
        }
        public static IServiceCollection AddApiJwtAuthentication(
            this IServiceCollection services,
            JWTOptions tokenOptions)
        {
            if (tokenOptions == null)
            {
                throw new ArgumentNullException(
                          $"{nameof(tokenOptions)} is a required parameter. " +
                          "Please make sure you've provided a valid instance with the appropriate values configured.");
            }

            services.AddScoped <IJWTTokenGenerator, JWTTokenGenerator>(serviceProvider =>
                                                                       new JWTTokenGenerator(tokenOptions));

            services.AddIdentity <User, Role>(opt =>
            {
                opt.Password.RequiredLength         = 6;
                opt.Password.RequireDigit           = false;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <DataContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew                = TimeSpan.FromSeconds(5),
                    ValidateAudience         = true,
                    ValidAudience            = tokenOptions.Audience,
                    ValidateIssuer           = true,
                    ValidIssuer              = tokenOptions.Issuer,
                    IssuerSigningKey         = tokenOptions.SigningKey,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(AdministratorPolicy, policy => policy.RequireRole(nameof(Role.Types.Administrator)));
                options.AddPolicy(TeacherUserPolicy, policy => policy.RequireRole(nameof(Role.Types.Teacher)));
                options.AddPolicy(StudentUserPolicy, policy => policy.RequireRole(nameof(Role.Types.Student)));
            });

            return(services);
        }
        public void testPositive_JustSign()
        {
            JWTOptions options1 = new JWTOptions();

            options1.SetSecret(hexaKey);
            bool verification = jwt.DoVerifyJustSignature(token, "HS256", options1);

            True(verification, jwt);
        }
        public void TestNegative_JustSign()
        {
            JWTOptions options1 = new JWTOptions();
            string     hexaKey1 = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options1.SetSecret(hexaKey1);
            bool verification = jwt.DoVerifyJustSignature(token, "HS256", options1);

            Assert.IsFalse(verification);
            Assert.IsTrue(jwt.HasError());
        }
        private void AddHeaderParameters(JwtHeader header, JWTOptions options)
        {
            HeaderParameters            parameters = options.GetHeaderParameters();
            List <string>               list       = parameters.GetAll();
            Dictionary <string, object> map        = parameters.GetMap();

            foreach (string s in list)
            {
                header.Add(s.Trim(), ((string)map[s]).Trim());
            }
        }
Exemple #15
0
 public AccountController(UserManager <ApplicationUser> userManager,
                          RoleManager <IdentityRole> roleManager,
                          SignInManager <ApplicationUser> signInManager,
                          IOptionsSnapshot <JWTOptions> jwtSettings,
                          IMapper modelMapper)
 {
     this._userManager   = userManager;
     this._roleManager   = roleManager;
     this._signInManager = signInManager;
     this._modelMapper   = modelMapper;
     this._jwtOptions    = jwtSettings.Value ?? throw new ArgumentNullException("JWT Settings must be filled!");
 }
Exemple #16
0
        public virtual void SetUp()
        {
            keyGenerator = new SymmetricKeyGenerator();
            jwt          = new JWTCreator();
            options      = new JWTOptions();
            claims       = new PrivateClaims();

            string hexaKey = keyGenerator.doGenerateKey("GENERICRANDOM", 256);

            options.SetSecret(hexaKey);

            claims.setClaim("hola1", "hola1");
        }
        public virtual void SetUp()
        {
            options = new JWTOptions();
            jwt     = new JWTCreator();
            claims  = new PrivateClaims();
            keyGen  = new SymmetricKeyGenerator();

            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");
            ID = "0696bb20-6223-4a1c-9ebf-e15c74387b9c, 0696bb20-6223-4a1c-9ebf-e15c74387b9c";            // &guid.Generate()
            options.AddRegisteredClaim("jti", ID);
            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");
        }
        public void TestNegative3()
        {
            JWTOptions op = new JWTOptions();

            op.AddRegisteredClaim("aud", "jitsi");
            op.AddRegisteredClaim("iss", "my_client");
            op.AddRegisteredClaim("sub", "meet.jit.si");
            op.SetSecret(hexaKey);
            //op.AddHeaderParameter("pepe", "whatever");

            bool verification = jwt.DoVerify(token, "HS256", claims, op);

            // Assert.IsFalse(verification);
            Assert.IsFalse(jwt.HasError());
        }
        private bool VerifyHeader(JwtSecurityToken jwtToken, JWTOptions options)
        {
            int claimsNumber            = jwtToken.Header.Count;
            HeaderParameters parameters = options.GetHeaderParameters();

            if (parameters.IsEmpty() && claimsNumber == 2)
            {
                return(true);
            }
            if (parameters.IsEmpty() && claimsNumber > 2)
            {
                return(false);
            }

            List <String> allParms = parameters.GetAll();

            if (claimsNumber != allParms.Count + 2)
            {
                return(false);
            }
            Dictionary <String, Object> map = parameters.GetMap();


            foreach (string s in allParms)
            {
                if (!jwtToken.Header.ContainsKey(s.Trim()))
                {
                    return(false);
                }


                string claimValue = null;
                try
                {
                    claimValue = (string)jwtToken.Header[s.Trim()];
                }
                catch (Exception)
                {
                    return(false);
                }
                String optionsValue = ((string)map[s]).Trim();
                if (!SecurityUtils.compareStrings(claimValue, optionsValue.Trim()))
                {
                    return(false);
                }
            }
            return(true);
        }
        public virtual void SetUp()
        {
            keyGenerator = new SymmetricKeyGenerator();
            jwt          = new JWTCreator();
            options      = new JWTOptions();
            claims       = new PrivateClaims();

            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");

            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");

            path_RSA_sha256_1024 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha256_1024");
        }
        public virtual void SetUp()
        {
            guid    = new GUID();
            jwt     = new JWTCreator();
            options = new JWTOptions();
            claims  = new PrivateClaims();

            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");

            options.AddRegisteredClaim("jti", guid.Generate());

            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");

            ECDSA_path = Path.Combine(BASE_PATH, "dummycerts", "JWT_ECDSA");
        }
 private bool validateRegisteredClaims(JwtSecurityToken jwtToken, JWTOptions options)
 {
     // Adding registered claims
     if (options.hasRegisteredClaims())
     {
         RegisteredClaims registeredClaims = options.getAllRegisteredClaims();
         List <Claim>     registeredC      = registeredClaims.getAllClaims();
         foreach (Claim registeredClaim in registeredC)
         {
             string registeredClaimKey   = registeredClaim.getKey();
             object registeredClaimValue = registeredClaim.getValue();
             if (RegisteredClaimUtils.exists(registeredClaimKey))
             {
                 if (!RegisteredClaimUtils.isTimeValidatingClaim(registeredClaimKey))
                 {
                     if (!RegisteredClaimUtils.validateClaim(registeredClaimKey, (string)registeredClaimValue, 0, jwtToken, this.error))
                     {
                         return(false);
                     }
                 }
                 else
                 {
                     long customValidationTime = registeredClaims.getClaimCustomValidationTime(registeredClaimKey);
                     //int value = (int)registeredClaimValue;
                     if (!RegisteredClaimUtils.validateClaim(registeredClaimKey, (string)registeredClaimValue, customValidationTime, jwtToken, this.error))
                     {
                         return(false);
                     }
                 }
                 if (this.HasError())
                 {
                     return(false);
                 }
             }
             else
             {
                 error.setError("JW002", registeredClaimKey + " wrong registered claim key");
                 return(false);
             }
         }
     }
     return(true);
 }
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

            if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var token) && !string.IsNullOrEmpty(token))
            {
                var result        = JWTOptions.Validate(token.ToString(), out var login, out var validTo);
                var isItLastToken = _users.IsItLastToken(login, token, validTo);
                if (result == 0 && isItLastToken)
                {
                    context.Response.Headers["Sec-WebSocket-Protocol"] = token;
                    var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);

                    _webSocketHandler.OnConnected(socket, login);

                    await Receive(socket, async (result, serializedMessage) =>
                    {
                        if (result.MessageType == WebSocketMessageType.Text)
                        {
                            await _webSocketHandler.ReceiveAsync(socket, result, serializedMessage).ConfigureAwait(false);
                            return;
                        }
                        else if (result.MessageType == WebSocketMessageType.Close)
                        {
                            try
                            {
                                await _webSocketHandler.OnDisconnected(socket);
                            }
                            catch (WebSocketException)
                            {
                                throw; //let's not swallow any exception for now
                            }
                            return;
                        }
                    });
                }
            }
        }
Exemple #24
0
        public async Task InvokeAsync(HttpContext context)
        {
            var authorization = context.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authorization.ToString()))
            {
                var token  = authorization.ToString().Substring(bearer.Length);
                var result = JWTOptions.Validate(token, out var login, out var validTo);

                if (result != 0)
                {
                    if (result == 2)
                    {
                        context.Response.StatusCode = 403;
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                    }

                    await context.Response.WriteAsync("Token is invalid");
                }
                else
                {
                    if (_users.IsItLastToken(login, token, validTo))
                    {
                        context.Request.Headers.Add("UserLogin", new StringValues(login));
                        await _next.Invoke(context);
                    }
                    else
                    {
                        context.Response.StatusCode = 401;
                        await context.Response.WriteAsync("Token is invalid (new connection opened somewhere)");
                    }
                }
            }
            else
            {
                await _next.Invoke(context);
            }
        }
        public virtual void SetUp()
        {
            jwt     = new JWTCreator();
            options = new JWTOptions();
            keyGen  = new SymmetricKeyGenerator();
            claims  = new PrivateClaims();

            options.AddCustomTimeValidationClaim("exp", "2020/07/20 17:56:51", "20");
            options.AddCustomTimeValidationClaim("iat", "2020/07/20 17:56:51", "20");
            options.AddCustomTimeValidationClaim("nbf", "2020/07/20 17:56:51", "20");
            claims.setClaim("hola1", "hola1");
            string hexaKey = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options.SetSecret(hexaKey);
            string token = jwt.DoCreate("HS256", claims, options);

            payload = jwt.GetPayload(token);


            expected = "{\"hola1\":\"hola1\",\"exp\":1595267811,\"iat\":1595267811,\"nbf\":1595267811}";
        }
Exemple #26
0
        public virtual void SetUp()
        {
            du           = new DateUtil();
            guid         = new GUID();
            keyGenerator = new SymmetricKeyGenerator();
            jwt          = new JWTCreator();
            options      = new JWTOptions();
            claims       = new PrivateClaims();

            options.AddRegisteredClaim("iss", "GXSA");
            options.AddRegisteredClaim("sub", "subject1");
            options.AddRegisteredClaim("aud", "audience1");

            options.AddRegisteredClaim("jti", guid.Generate());


            options.AddCustomTimeValidationClaim("iat", du.GetCurrentDate(), "20");
            options.AddCustomTimeValidationClaim("nbf", du.GetCurrentDate(), "20");

            claims.setClaim("hola1", "hola1");
            claims.setClaim("hola2", "hola2");
        }
        // äîáàâëåíèå è íàñòðîéêà ñåðâèñîâ, èñïîëüçóåìûõ ïðèëîæåíèåì
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(optionsBuilder =>
                                                optionsBuilder.UseSqlServer(Configuration.GetConnectionString("Connection")));

            var section    = Configuration.GetSection("AuthOptions");
            var options    = section.Get <AuthOptions>();
            var jwtOptions = new JWTOptions(options.Issuer, options.Audience, options.Secret, options.Lifetime);

            services.AddApiJwtAuthentication(jwtOptions);

            services.Configure <SeedOptions>(Configuration.GetSection("Seed"));
            services.AddAsyncInitializer <IdentityInitializer>()
            .AddAsyncInitializer <StudyDataInitializer>();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost:3000", "http://localhost:3000", "https://localhost:44303")
                    //builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            services.AddControllers();

            services.AddTransient <IAccountService, AuthService>()
            .AddTransient <IAdminService, AdminService>()
            .AddTransient <ITaskService, TaskService>()
            .AddTransient <ITeacherService, TeacherService>()
            .AddTransient <IStudentService, StudentService>()
            .AddTransient <IRepoService, RepoService>()
            .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddScoped <IUserValidator <User>, UserValidator <User> >();
        }
Exemple #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //AddTransient瞬时模式:每次请求,都获取一个新的实例。即使同一个请求获取多次也会是不同的实例
            //AddScoped:每次请求,都获取一个新的实例。同一个请求获取多次会得到相同的实例
            //AddSingleton单例模式:每次都获取同一个实例

            var jwtOptions = new JWTOptions();

            Configuration.Bind("JwtOptions", jwtOptions);
            services.AddJwtBearerExt(jwtOptions);

            services.AddCorsExt();
            #region 注册Swagger服务
            services.AddApiVersionExt();
            services.AddSwaggerGenExt();
            #endregion
            services.AddControllers()
            .AddNewtonsoftJsonExt();

            services.AddEasyCachingExt(Configuration);
            //services.AddCsRedisByEasyCaching();
            services.AddCsRedisHelper(Configuration);
        }
Exemple #29
0
        private void SetupJWT(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = JWTOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = JWTOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = JWTOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true
                };
            });

            services.AddAuthorization();
        }
        public virtual void SetUp()
        {
            jwt     = new JWTCreator();
            options = new JWTOptions();
            du      = new DateUtil();
            keyGen  = new SymmetricKeyGenerator();
            claims  = new PrivateClaims();



            hexaKey = keyGen.doGenerateKey("GENERICRANDOM", 256);

            options.AddRegisteredClaim("aud", "jitsi");
            options.AddRegisteredClaim("iss", "my_client");
            options.AddRegisteredClaim("sub", "meet.jit.si");


            claims.setClaim("hola", "hola");

            options.AddHeaderParameter("cty", "twilio-fpa;v=1");
            options.SetSecret(hexaKey);

            token = jwt.DoCreate("HS256", claims, options);
        }