Esempio n. 1
0
        public async Task <IActionResult> GetToken([FromBody] LoginRequestModel model)
        {
            //Get user & validate password.
            var user = await _userSecurityMgr.GetUserForLogin(model.Username, model.Password);

            //if that didn't return a user, then either name or password is not valid, so nah.
            if (user == null)
            {
                return(Unauthorized());
            }

            var tokenBuilder = new JwtTokenBuilder()
                               .AddSecurityKey(JwtSecurityKey.Create(_settingsService.JwtSecret))
                               .AddSubject(user.UserName)
                               .AddIssuer(_settingsService.JwtIssuer)
                               .AddAudience(_settingsService.JwtAudience)
                               .AddClaim("MembershipId", user.Id);

            //add all known roles to claim.
            foreach (var role in _userSecurityMgr.GetRolesForUser(user))
            {
                tokenBuilder = tokenBuilder.AddClaim("roles", role);
            }

            tokenBuilder = tokenBuilder
                           .AddExpiry(_settingsService.TokenLifeTimeInMinutes);

            var token = tokenBuilder.Build();

            return(Ok(token.Value));
        }
Esempio n. 2
0
        public static void ConfigJWTToken(IServiceCollection services, IConfigurationRoot Configuration)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = SWCmsConstants.JWTSettings.ISSUER,
                    ValidAudience    = SWCmsConstants.JWTSettings.AUDIENCE,
                    IssuerSigningKey =
                        JwtSecurityKey.Create(SWCmsConstants.JWTSettings.SECRET_KEY)
                };
                //options.Events = new JwtBearerEvents
                //{
                //    OnAuthenticationFailed = context =>
                //    {
                //        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                //        return Task.CompletedTask;
                //    },
                //    OnTokenValidated = context =>
                //    {
                //        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                //        return Task.CompletedTask;
                //    }
                //};
            });
        }
Esempio n. 3
0
        public IActionResult Login([FromBody] LoginViewModel inputModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Hibás felhasználónév vagy jelszó!"));
            }

            var currentUser = _userService.getUserByName(inputModel.UserName);

            if (currentUser == null)
            {
                return(NotFound("Nincs ilyen felhasználó regisztrálva!"));
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("Security key required for ShelterApp"))
                        .AddSubject(currentUser.Username)
                        .AddIssuer("ShelterServer")
                        .AddAudience("ShelterApp")
                        .AddClaim("MembershipId", currentUser.Id.ToString())
                        .AddExpiry(300)
                        .Build();

            var responseObject = new LoginResponseModel
            {
                User  = currentUser,
                Token = token.Value
            };

            return(Ok(responseObject));
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "JWTSample",
                    ValidAudience    = "JWTSample",
                    IssuerSigningKey = JwtSecurityKey.Create("jwt-sample-key-123456")
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        return(Task.CompletedTask);
                    }
                };
            });
        }
Esempio n. 5
0
        public IActionResult Create([FromBody] LoginInputModel inputModel)
        {
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = _signInManager.PasswordSignInAsync(inputModel.Username, inputModel.Password, true, lockoutOnFailure: false).Result;
                if (!result.Succeeded)
                {
                    return(Unauthorized());
                }

                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                            .AddSubject("james bond")
                            .AddIssuer("Fiver.Security.Bearer")
                            .AddAudience("Fiver.Security.Bearer")
                            .AddClaim("MembershipId", "111")
                            .AddExpiry(1)
                            .Build();

                //return Ok(token);
                return(Ok(token.Value));
            }

            return(NotFound());
        }
Esempio n. 6
0
        public IActionResult RequestToken([FromBody] UsuarioViewModel request)
        {
            if (request == null)
            {
                return(NotFound("Paramentros Inválidos"));
            }

            if (request.Nome != _configuration.GetSection("Usuario").Value || request.Senha != _configuration.GetSection("Senha").Value)
            {
                return(Unauthorized());
            }

            var Expiry = Convert.ToInt32(_configuration.GetSection("Expiry").Value);

            var token = new TokenJWTBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration.GetSection("SecurityKey").Value))
                        .AddSubject(_configuration.GetSection("Subject").Value)
                        .AddIssuer(_configuration.GetSection("Issuer").Value)
                        .AddAudience(_configuration.GetSection("Audience").Value)
                        .AddClaim(_configuration.GetSection("Claim").Value, _configuration.GetSection("ClaimNumber").Value)
                        .AddExpiry(Expiry)
                        .Builder();

            return(Ok(token.value));
        }
Esempio n. 7
0
 protected void ConfigJWTToken(IServiceCollection services, IConfiguration Configuration)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
         options.TokenValidationParameters =
             new TokenValidationParameters
         {
             ClockSkew                = TimeSpan.FromMinutes(SioService.GetAuthConfig <int>("ClockSkew")),
             ValidateIssuer           = false,
             ValidateAudience         = false,
             ValidateLifetime         = true,
             ValidateIssuerSigningKey = true,
             ValidIssuer              = SioService.GetAuthConfig <string>("Issuer"),
             ValidAudience            = SioService.GetAuthConfig <string>("Audience"),
             IssuerSigningKey         = JwtSecurityKey.Create(SioService.GetAuthConfig <string>("SecretKey"))
         };
         options.Events = new JwtBearerEvents
         {
             OnAuthenticationFailed = context =>
             {
                 Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                 return(Task.CompletedTask);
             },
             OnTokenValidated = context =>
             {
                 Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                 return(Task.CompletedTask);
             }
         };
     });
 }
        public IActionResult Login(LoginView user)
        {
            //if (ModelState.IsValid)
            //{
            //    MembershipContext _userContext = _membershipService.ValidateUser(user.UserName, user.Password);
            //    if (_userContext.User != null)
            //    {
            //        Request.HttpContext.Response.Headers.Add("UserName", _userContext.Principal.Identity.Name);
            //        return new ContentResult { Content = "Successed!", StatusCode = (int)HttpStatusCode.OK, ContentType = "txt/html" };
            //    }
            //    else
            //        return new ContentResult { Content = "Failed", StatusCode = (int)HttpStatusCode.OK, ContentType = "txt/html" };
            //}
            //else
            //    return new ContentResult { StatusCode = (int)HttpStatusCode.BadRequest };


            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject("james bond")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();

            return(new JsonResult(token));
        }
Esempio n. 9
0
        private async Task <LoginResp> Login(string loginName, string password, string authCode, byte clientType, string clientId, bool regist = false)
        {
            var resp = new LoginResp();

            var ip      = Request.GetClientIP();
            var website = Request.GetReferer();

            var result = await _userService.Login(loginName, password, ip, website, clientType, clientId);

            if (result.NonzeroCode)
            {
                return(resp.Fail(result.Msg));
            }

            // 生成本次登录的标识
            string loginId = $"__{ip}_{DateTime.Now.ToString("yyMMddHHmmssfffffff")}";

            // 生成 Token
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_jwtOptions.Secret))
                        .AddIssuer(_jwtOptions.Issuer)
                        .AddAudience(_jwtOptions.Audience)
                        .AddClaim(Constants.LOGINNAME, loginName)
                        .AddClaim(Constants.LOGINID, loginId)
                        .AddExpiry(_jwtOptions.Expiry)
                        .Build();

            // 写入缓存,以便 TokenSessionFilter使用
            await _redisClient.GetDatabase().StringSetAsync(loginName, loginId, TimeSpan.FromMinutes(_jwtOptions.Expiry));

            resp.AccessToken = token.Value;
            resp.TokenType   = "Bearer";
            return(resp);
        }
Esempio n. 10
0
        public async Task <IActionResult> Create([FromBody] JwtLoginInputModel inputModel)
        {
            var user = await _userManager.FindByNameAsync(inputModel.Username);

            if (user == null)
            {
                return(Unauthorized());
            }

            // Validate the username/password parameters and ensure the account is not locked out.
            var result = await _signInManager.CheckPasswordSignInAsync(user, inputModel.Password, lockoutOnFailure : true);

            if (!result.Succeeded)
            {
                return(Unauthorized());
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("fiver-secret-key"))
                        .AddSubject("james bond")
                        .AddIssuer("Fiver.Security.Bearer")
                        .AddAudience("Fiver.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();

            //return Ok(token);
            return(Ok(token.Value));
        }
Esempio n. 11
0
        /// <summary>
        /// Método en donde se define los parámetros que tendrá
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "DCICC.Inventarios.Seguridad.Bearer",
                    ValidAudience    = "DCICC.Inventarios.Seguridad.Bearer",
                    IssuerSigningKey = JwtSecurityKey.Create("DCICC.Inventarios.Secret.Key")
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Logs.Error("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Logs.Info("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Member", policy => policy.RequireClaim("DCICC.Inventarios.MemberId"));
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Esempio n. 12
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <FormOptions>(options =>
            {
                options.MemoryBufferThreshold = Int32.MaxValue;
            });
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);
            var appSettings = Configuration.GetSection(nameof(AppSettings)).Get <AppSettings>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = JwtSecurityKey.UseDynamicToken,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = appSettings.Issuer,
                    ValidAudience    = appSettings.Audience,
                    IssuerSigningKey = JwtSecurityKey.Create(appSettings.SecretKey)
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext <EntityContext>(opt => opt.UseInMemoryDatabase("EntityDatabase"));
            services.AddTransient <QuantityOnHandFileParser, ByteArrayQuantityOnHandFileParser>();
            services.AddTransient <HttpRequestFileExtractor, InMemoryHttpRequestFileExtractor>();
        }
Esempio n. 13
0
 protected void ConfigJWTToken(IServiceCollection services, IConfiguration Configuration)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
         options.RequireHttpsMetadata      = false;
         options.SaveToken                 = true;
         options.TokenValidationParameters =
             new TokenValidationParameters
         {
             ClockSkew                = TimeSpan.Zero,//.FromMinutes(MixService.GetAuthConfig<int>("ClockSkew")), //x minute tolerance for the expiration date
             ValidateIssuer           = MixService.GetAuthConfig <bool>("ValidateIssuer"),
             ValidateAudience         = MixService.GetAuthConfig <bool>("ValidateAudience"),
             ValidateLifetime         = MixService.GetAuthConfig <bool>("ValidateLifetime"),
             ValidateIssuerSigningKey = MixService.GetAuthConfig <bool>("ValidateIssuerSigningKey"),
             ValidIssuer              = MixService.GetAuthConfig <string>("Issuer"),
             ValidAudience            = MixService.GetAuthConfig <string>("Audience"),
             IssuerSigningKey         = JwtSecurityKey.Create(MixService.GetAuthConfig <string>("SecretKey"))
         };
         options.Events = new JwtBearerEvents
         {
             OnAuthenticationFailed = context =>
             {
                 Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                 return(Task.CompletedTask);
             },
             OnTokenValidated = context =>
             {
                 Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                 return(Task.CompletedTask);
             },
         };
     });
 }
Esempio n. 14
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 => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "laudson.com.br",
                    ValidAudience    = "laudson.com.br",
                    IssuerSigningKey = JwtSecurityKey.Create("a-password-very-big-to-be-good")
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddMvc();
            services.AddDbContext <CoreDbContext>(Options => Options.UseSqlServer(Configuration.GetConnectionString("Default")));
        }
Esempio n. 15
0
        public async Task <string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
        {
            var claims = new[]
            {
                //new Claim(JwtRegisteredClaimNames.UniqueName, userName),
                //new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                //new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
            };

            //var _claims = new Dictionary<string, string>();
            //_claims.Add(identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role).Type, identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Role).Value);
            //_claims.Add(identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id).Type, identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id).Value);

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create())
                        .AddSubject("RCM-API")
                        .AddIssuer(_jwtOptions.Issuer)
                        .AddAudience(_jwtOptions.Audience)
                        .AddClaim(JwtRegisteredClaimNames.UniqueName, userName)
                        .AddClaims(claims)
                        //.AddClaims(_claims)
                        .AddExpiry(100)
                        .Build();

            return(token.Value);
        }
Esempio n. 16
0
        public TokensData UpdateAccessToken(Tokens tokens, int id, out dynamic key)
        {
            var user = userService.GetUserByName(tokens);

            key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"]));
            //var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            Console.WriteLine(key);
            var expiry = DateTime.Now.AddMinutes(5);

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration["SecurityKey"]))
                        .AddSubject("test123 test123")
                        .AddIssuer("SalesMarket.Security.Bearer")
                        .AddAudience("SalesMarket.Security.Bearer")
                        .AddClaim("MembershipId", "111")
                        .AddExpiry(1)
                        .Build();
            TokensData tokensData = new TokensData
            {
                Token       = token.Value,
                ExpiryToken = expiry,
                AddedDate   = DateTime.Now,
                LastUpdate  = DateTime.Now,
                UsersId     = id
            };

            return(tokensData);
        }
Esempio n. 17
0
        public async Task <string> GenerateTokenAsync(
            ApplicationUser user,
            DateTime expires,
            string refreshToken,
            string aesKey,
            string rsaPublicKey,
            MixAuthenticationConfigurations appConfigs)
        {
            List <Claim> claims = await GetClaimsAsync(user, appConfigs);

            claims.AddRange(new[]
            {
                new Claim(MixClaims.Id, user.Id.ToString()),
                new Claim(MixClaims.Username, user.UserName),
                new Claim(MixClaims.RefreshToken, refreshToken),
                new Claim(MixClaims.AESKey, aesKey),
                new Claim(MixClaims.RSAPublicKey, rsaPublicKey)
            });
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: appConfigs.Issuer,
                audience: appConfigs.Audience,
                claims: claims,
                notBefore: expires.AddMinutes(-appConfigs.AccessTokenExpiration),
                expires: expires,
                signingCredentials: new SigningCredentials(JwtSecurityKey.Create(appConfigs.SecretKey), SecurityAlgorithms.HmacSha256));

            return(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken));
        }
        protected override void ConfigureAuthenticationServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = JwtTokenBuilder.ValidIssuer,
                    ValidAudience    = JwtTokenBuilder.ValidAudience,
                    IssuerSigningKey =
                        JwtSecurityKey.Create(JwtTokenBuilder.KeySource)
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("User", policy => policy.RequireClaim("jobTitle", "Advanced"));
                options.AddPolicy("Scope", policy => policy.RequireClaim(Configuration["AzureAdB2C:ScopePath"], Configuration["AzureAdB2C:ScopeRequired"]));
            });
        }
Esempio n. 19
0
        public void ConfigureServices(IServiceCollection services)
        {
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateLifetime         = true,
                ValidateAudience         = false,
                ValidateIssuer           = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = JwtSecurityKey.Create()
            };

            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseSqlite("DataSource=shop.db"));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(
                options =>
            {
                options.TokenValidationParameters = tokenValidationParameters;
            }
                );

            services.AddAuthorization();

            services.AddControllersWithViews();
        }
Esempio n. 20
0
        public async Task <LoginModel> Login(LoginModel data)
        {
            if (!string.IsNullOrEmpty(data.Username) &&
                !string.IsNullOrEmpty(data.Password))
            {
                var user = await this._repo.GetByEmailOrNumber(data.Username);

                data.Password = AppHelper.Instance.GetHash(data.Password);
                if (user != null)
                {
                    if (data.Password == user.Password)
                    {
                        data.Token = new JwtTokenBuilder()
                                     .AddSecurityKey(JwtSecurityKey.Create(user.ID.ToString()))
                                     .AddSubject(user.Email)
                                     .AddIssuer("Security.Bearer")
                                     .AddAudience("Security.Bearer")
                                     .AddClaim("IsAdmin", "true")
                                     .AddExpiry(5)
                                     .Build();
                    }

                    else
                    {
                        data.Token = "wrong password";
                    }
                }
            }
            data.Password = null;
            return(data);
        }
        public async Task <IActionResult> CreateToken([FromBody] InputModel Input)
        {
            if (string.IsNullOrWhiteSpace(Input.Email) || string.IsNullOrWhiteSpace(Input.Password))
            {
                return(Unauthorized());
            }

            var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, false, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                var token = new TokenJWTBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create("Secret_Key-12345678"))
                            .AddSubject("Empresa E-Commerce")
                            .AddIssuer("Teste.Securiry.Bearer")
                            .AddAudience("Teste.Securiry.Bearer")
                            .AddClaim("UsuarioAPINumero", "1")
                            .AddExpiry(5)
                            .Builder();

                return(Ok(token.value));
            }
            else
            {
                return(Unauthorized());
            }
        }
Esempio n. 22
0
        public IActionResult RefreshToken([FromBody] UserLogin data)
        {
            var _refreshToken = db.RefreshTokens.SingleOrDefault(m => m.Refreshtoken == data.refreshToken);
            var role          = db.Roles.Where(x => x.Id == data.RoleId).FirstOrDefault().Name;

            if (_refreshToken == null)
            {
                return(Ok(null));
            }
            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(_configuration.GetValue <string>("JwtSecretKey")))
                        .AddIssuer(_configuration.GetValue <string>("JwtIssuer"))
                        .AddAudience(_configuration.GetValue <string>("JwtAudience"))
                        .AddExpiry(60)
                        .AddClaim("Email", data.username)
                        .AddRole(role)
                        .Build();

            _refreshToken.Refreshtoken = Guid.NewGuid().ToString();
            db.RefreshTokens.Update(_refreshToken);
            db.SaveChanges();
            data.Token        = token.Value;
            data.refreshToken = _refreshToken.Refreshtoken;

            return(Ok(data));
        }
Esempio n. 23
0
        public async Task <IActionResult> Create([FromBody] RegistrationLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Unauthorized());
            }

            var userVerified = await _acctSvc.VerifyUserAsync(model);

            if (userVerified != null)
            {
                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(_config.GetSection("JwtSettings:SecurityKey").Value))
                            .AddSubject(model.Email)
                            .AddIssuer(_config.GetSection("AppConfiguration:Issuer").Value)
                            .AddAudience(_config.GetSection("AppConfiguration:Issuer").Value)
                            //.AddClaim("SellerId", userVerified.Id.ToString())
                            .AddExpiry(10)
                            .Build();

                TokenModel tokenModel = new TokenModel
                {
                    AccessToken = token.Value,
                    SellerId    = userVerified.Id,
                    Email       = model.Email
                };

                return(Ok(tokenModel));
            }

            return(BadRequest());
        }
Esempio n. 24
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 => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = "Security.Bearer",
                    ValidAudience    = "Security.Bearer",
                    IssuerSigningKey = JwtSecurityKey.Create("this is my custom Secret key for authentication")
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });
            services.AddMvc();
        }
Esempio n. 25
0
        public Entity.API.LoginResponse Buscar(string login, string password)
        {
            var usr = _UsuarioRepository.Buscar(login, password);

            if (usr != null && !string.IsNullOrEmpty(usr.Login))
            {
                IConfigurationSection jwtAppSettingOptions = _configuration.GetSection("JwtIssuerOptions");
                var secretKey  = jwtAppSettingOptions["SecretKey"];
                var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(signingKey.ToString()))
                            .AddIssuer(jwtAppSettingOptions["Issuer"])
                            .AddAudience(jwtAppSettingOptions["Audience"])
                            .AddExpiry(1)
                            .AddClaim(ClaimTypes.NameIdentifier, usr.Nome)
                            .AddClaim(ClaimTypes.Name, usr.Login)
                            .AddClaim(ClaimTypes.Role, "USUARIO")
                            .Build();

                var resultMapped = _mapper.Map <Entity.API.LoginResponse>(usr);
                resultMapped.ChaveJwt = token.Value;

                return(resultMapped);
            }
            else
            {
                return(new Entity.API.LoginResponse());
            }
        }
        //[Route("logOut/{refreshTokenId}")]
        //[HttpGet]
        //public async Task<RepositoryResponse<bool>> Logout(string refreshTokenId)
        //{
        //    var result = await RefreshTokenViewModel.Repository.RemoveListModelAsync(t => t.Id == refreshTokenId);
        //    return result;
        //}

        //[Route("logOutOther/{refreshTokenId}")]
        //[HttpGet]
        //public async Task<RepositoryResponse<bool>> LogoutOther(string refreshTokenId)
        //{
        //    return await RefreshTokenViewModel.LogoutOther(refreshTokenId);
        //}

        /*
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
         * {
         *  // Ensure the user has gone through the username & password screen first
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  var model = new LoginWith2faViewModel { RememberMe = rememberMe };
         *  ViewData["ReturnUrl"] = returnUrl;
         *
         *  return View(model);
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
         *  }
         *
         *  var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
         *
         *  var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
         *
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  else if (result.IsLockedOut)
         *  {
         *      _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
         *      return RedirectToAction(nameof(Login));
         *  }
         *  else
         *  {
         *      _logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
         *      ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
         *      return View();
         *  }
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
         * {
         *  // Ensure the user has gone through the username & password screen first
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  ViewData["ReturnUrl"] = returnUrl;
         *
         *  return View();
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *
         *  var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load two-factor authentication user.");
         *  }
         *
         *  var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
         *
         *  var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
         *
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  if (result.IsLockedOut)
         *  {
         *      _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
         *      return RedirectToAction(nameof(Login));
         *  }
         *  else
         *  {
         *      _logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id);
         *      ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
         *      return View();
         *  }
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public IActionResult ExternalLogin(string provider, string returnUrl = null)
         * {
         *  // Request a redirect to the external login provider.
         *  var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
         *  var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
         *  return Challenge(properties, provider);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
         * {
         *  if (remoteError != null)
         *  {
         *      ErrorMessage = $"Error from external provider: {remoteError}";
         *      return RedirectToAction(nameof(Login));
         *  }
         *  var info = await _signInManager.GetExternalLoginInfoAsync();
         *  if (info == null)
         *  {
         *      return RedirectToAction(nameof(Login));
         *  }
         *
         *  // Sign in the user with this external login provider if the user already has a login.
         *  var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
         *  if (result.Succeeded)
         *  {
         *      _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
         *      return RedirectToLocal(returnUrl);
         *  }
         *  if (result.IsLockedOut)
         *  {
         *      return RedirectToAction(nameof(Login)); // LogOut
         *  }
         *  else
         *  {
         *      // If the user does not have an account, then ask the user to create an account.
         *      ViewData["ReturnUrl"] = returnUrl;
         *      ViewData["LoginProvider"] = info.LoginProvider;
         *      var email = info.Principal.FindFirstValue(ClaimTypes.Email);
         *      return View("ExternalLogin", new ExternalLoginViewModel { Email = email });
         *  }
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      // Get the information about the user from the external login provider
         *      var info = await _signInManager.GetExternalLoginInfoAsync();
         *      if (info == null)
         *      {
         *          throw new ApplicationException("Error loading external login information during confirmation.");
         *      }
         *      var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
         *      var result = await _userManager.CreateAsync(user);
         *      if (result.Succeeded)
         *      {
         *          result = await _userManager.AddLoginAsync(user, info);
         *          if (result.Succeeded)
         *          {
         *              await _signInManager.SignInAsync(user, isPersistent: false);
         *              _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
         *              return RedirectToLocal(returnUrl);
         *          }
         *      }
         *      AddErrors(result);
         *  }
         *
         *  ViewData["ReturnUrl"] = returnUrl;
         *  return View(nameof(ExternalLogin), model);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public async Task<IActionResult> ConfirmEmail(string userId, string code)
         * {
         *  if (userId == null || code == null)
         *  {
         *      return RedirectToAction("Index", "Home");
         *  }
         *  var user = await _userManager.FindByIdAsync(userId);
         *  if (user == null)
         *  {
         *      throw new ApplicationException($"Unable to load user with ID '{userId}'.");
         *  }
         *  var result = await _userManager.ConfirmEmailAsync(user, code);
         *  return View(result.Succeeded ? "ConfirmEmail" : "Error");
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ForgotPassword()
         * {
         *  return View();
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      var user = await _userManager.FindByEmailAsync(model.Email);
         *      if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
         *      {
         *          // Don't reveal that the user does not exist or is not confirmed
         *          return RedirectToAction(nameof(ForgotPasswordConfirmation));
         *      }
         *
         *      // For more information on how to enable account confirmation and password reset please
         *      // visit https://go.microsoft.com/fwlink/?LinkID=532713
         *      var code = await _userManager.GeneratePasswordResetTokenAsync(user);
         *      var callbackUrl = "";
         *      await _emailSender.SendEmailAsync(model.Email, "Reset Password",
         *         $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
         *      return RedirectToAction(nameof(ForgotPasswordConfirmation));
         *  }
         *
         *  // If we got this far, something failed, redisplay form
         *  return View(model);
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ForgotPasswordConfirmation()
         * {
         *  return View();
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ResetPassword(string code = null)
         * {
         *  if (code == null)
         *  {
         *      throw new ApplicationException("A code must be supplied for password reset.");
         *  }
         *  var model = new ResetPasswordViewModel { Code = code };
         *  return View(model);
         * }
         *
         * [HttpPost]
         * [AllowAnonymous]
         * [ValidateAntiForgeryToken]
         * public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
         * {
         *  if (!ModelState.IsValid)
         *  {
         *      return View(model);
         *  }
         *  var user = await _userManager.FindByEmailAsync(model.Email);
         *  if (user == null)
         *  {
         *      // Don't reveal that the user does not exist
         *      return RedirectToAction(nameof(ResetPasswordConfirmation));
         *  }
         *  var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
         *  if (result.Succeeded)
         *  {
         *      return RedirectToAction(nameof(ResetPasswordConfirmation));
         *  }
         *  AddErrors(result);
         *  return View();
         * }
         *
         * [HttpGet]
         * [AllowAnonymous]
         * public IActionResult ResetPasswordConfirmation()
         * {
         *  return View();
         * }
         *
         * [HttpGet]
         * public IActionResult AccessDenied()
         * {
         *  return View();
         * }
         *
         #region Helpers
         *
         * private void AddErrors(IdentityResult result)
         * {
         *  foreach (var error in result.Errors)
         *  {
         *      ModelState.AddModelError(string.Empty, error.Description);
         *  }
         * }
         *
         * private IActionResult RedirectToLocal(string returnUrl)
         * {
         *  if (Url.IsLocalUrl(returnUrl))
         *  {
         *      return Redirect(returnUrl);
         *  }
         *  else
         *  {
         *      return RedirectToAction("Index", "Home");
         *  }
         * }
         *
         #endregion Helpers
         *
         * //[AllowAnonymous]
         * [HttpPost]
         * public async Task<JsonResult> GenerateToken([FromBody] LoginViewModel model)
         * {
         *  if (ModelState.IsValid)
         *  {
         *      var user = await _userManager.FindByEmailAsync(model.Email);
         *
         *      if (user != null)
         *      {
         *          var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
         *          if (result.Succeeded)
         *          {
         *              var claims = new[]
         *              {
         * new Claim(JwtRegisteredClaimNames.Sub, user.Email),
         * new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
         * };
         *
         *              var creds = SWCmsConstants.AuthConfiguration.SigningCredentials;
         *
         *              var token = new JwtSecurityToken(SWCmsConstants.AuthConfiguration.AuthTokenIssuer,
         *                SWCmsConstants.AuthConfiguration.AuthTokenIssuer,
         *                claims,
         *                expires: DateTime.Now.AddMinutes(30),
         *                signingCredentials: creds);
         *
         *              return new JsonResult(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
         *          }
         *      }
         *  }
         *  return new JsonResult("Could not create token");
         * }
         *
         */

        private AccessTokenViewModel GenerateAccessToken(ApplicationUser user)
        {
            //string refreshToken = Guid.NewGuid().ToString();
            //var dtIssued = DateTime.UtcNow;
            //var dtExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration);
            //var dtRefreshTokenExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration);

            //RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel(
            //            new RefreshToken()
            //            {
            //                Id = refreshToken,
            //                Email = user.Email,
            //                IssuedUtc = dtIssued,
            //                ClientId = SWCmsConstants.AuthConfiguration.Audience,
            //                //Subject = SWCmsConstants.AuthConfiguration.Audience,
            //                ExpiresUtc = dtRefreshTokenExpired
            //            });

            //var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync();

            //if (saveRefreshTokenResult.IsSucceed)
            //{
            //    AccessTokenViewModel token = new AccessTokenViewModel()
            //    {
            //        Access_token = GenerateToken(user, dtExpired, refreshToken),
            //        //Refresh_token = vmRefreshToken.Id,
            //        Token_type = SWCmsConstants.AuthConfiguration.TokenType,
            //        Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration,
            //        //UserData = user,
            //        Issued = dtIssued,
            //        Expires = dtExpired,
            //    };
            //    return token;
            //}
            //else
            //{
            //    return null;
            //}

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create(SWCmsConstants.JWTSettings.SECRET_KEY))
                        .AddSubject(user.UserName)
                        .AddIssuer(SWCmsConstants.JWTSettings.ISSUER)
                        .AddAudience(SWCmsConstants.JWTSettings.AUDIENCE)
                        //.AddClaim("MembershipId", "111")
                        .AddExpiry(SWCmsConstants.JWTSettings.EXPIRED_IN)
                        .Build();
            AccessTokenViewModel access_token = new AccessTokenViewModel()
            {
                Access_token = token.Value, //GenerateToken(user, dtExpired, refreshToken),
                //Refresh_token = vmRefreshToken.Id,
                Token_type = SWCmsConstants.AuthConfiguration.TokenType,
                Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration,
                //UserData = user,
                Issued  = DateTime.UtcNow,
                Expires = token.ValidTo
            };

            return(access_token);
        }
Esempio n. 27
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

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

                    ValidIssuer      = Configuration.GetSection("Authentication:Issuer").Value,
                    ValidAudience    = Configuration.GetSection("Authentication:Audience").Value,
                    IssuerSigningKey = JwtSecurityKey.Create(Configuration.GetSection("Authentication:SecurityKey").Value)
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Administrator", policy => policy.RequireClaim("Administrator"));
                options.AddPolicy("Moderator", policy => policy.RequireClaim("Moderator"));
                options.AddPolicy("User", policy => policy.RequireClaim("User"));
            });

            services.AddMvc();

            services.Configure <Settings>(options =>
            {
                options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
                options.Database         = Configuration.GetSection("MongoConnection:Database").Value;
            });

            #region .   Repository   .
            services.AddTransient <IUserRepository, UserRepository>();
            #endregion
        }
Esempio n. 28
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 =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = JwtSecurityKey.Create(Configuration["Jwt:Key"])
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
            });
        }
Esempio n. 29
0
        public JsonResult Create([FromBody] LoginInputModel inputModel)
        {
            var audienceConfig       = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var expiresTime          = ConvertHelper.ConvertToInt(audienceConfig["ExpiresTime"]);
            var iss = audienceConfig["Iss"];
            var aud = audienceConfig["Aud"];

            if (inputModel.username == "admin" && inputModel.password == "12" && inputModel.client_secret == symmetricKeyAsBase64)
            {
                var token = new JwtTokenBuilder()
                            .AddSecurityKey(JwtSecurityKey.Create(inputModel.client_secret))
                            .AddSubject(inputModel.username)
                            .AddIssuer(iss)
                            .AddAudience(aud)
                            .AddClaim("scope", "openid pv btv tk bbt")
                            .AddClaim("NameSpace", inputModel.name_space)
                            .AddExpiry(expiresTime)
                            .Build();

                return(this.ToJson(token));
            }
            else
            {
                return(this.ToJson(Unauthorized()));
            }
        }
        public static AuthenticationBuilder AddFiverOAuth(this AuthenticationBuilder builder, string validIssuer, string validAudience, string securityKey)
        {
            builder.AddJwtBearer(options =>
            {
                options.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = validIssuer,
                    ValidAudience    = validAudience,
                    IssuerSigningKey = JwtSecurityKey.Create(securityKey)
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });
            return(builder);
        }