Exemplo n.º 1
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());
            }
        }
Exemplo n.º 2
0
        public IActionResult Login(LoginRequestDto request)
        {
            // sprawdzanie hasla w db
            string pass  = request.Passw;
            string index = request.IndexNumber;

            if (pass == null && index == null)
            {
                throw new Exception("Index number and password cannot be null.");
            }

            if (index == User.Identity.Name)
            {
            }
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, index),
                new Claim(ClaimTypes.Name, index),
                new Claim(ClaimTypes.Role, "employee")
            };
            //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(pass));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var keystring = key.ToString();
            var salt      = Encrypt.CreateSalt();
            var encrypted = Encrypt.Create(keystring, salt);

            var token = new JwtSecurityToken(

                issuer: "SandCorp",
                audience: "Employees",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: credentials

                );

            return(Ok(new
            {
                accessToken = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = Guid.NewGuid()
            }));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Login(UserLoginDTO loginDto)
        {
            //throw new  Exception("Custom Exceptios");
            // try
            // {
            var userExist = await _repo.Login(loginDto.Username.ToLower(), loginDto.Password);

            if (userExist == null)
            {
                return(Unauthorized());
            }
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userExist.Id.ToString()),
                new Claim(ClaimTypes.Name, userExist.UserName)
            };

            _loggger.LogInformation(_config.GetSection("AppSettings:Token").Value);

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            _loggger.LogInformation(key.ToString());
            var creds           = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);
            var tokenDiscriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDiscriptor);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token)
            }));

            // }
            // catch (System.Exception ex)
            // {

            //     _loggger.LogInformation(ex.Message);
            //     return BadRequest();
            // }
        }
Exemplo 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().AddJsonOptions(o =>
            {
                o.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "API LTM"
                });
            });

            var config = new AutoMapper.MapperConfiguration(
                c =>
            {
                c.AddProfile(new ConfigMapper());
            });

            var mapper = config.CreateMapper();

            services.AddSingleton(mapper);


            //Se quiser rodar com MongoDB
            ////**********************************////
            var contextMongo = new LTM.DAL.Context.MongoContext(Configuration.GetConnectionString("DefaultConnectionMongo"), Configuration.GetSection("DataBase").GetValue <string>("DbName"));
            var repProduto   = new DAL.Repository.MongoProdutoRepository(contextMongo);

            services.AddSingleton <DAL.Repository.IProdutoRepository>(repProduto);
            var repUsuario = new DAL.Repository.MongoUsuarioRepository(contextMongo);

            services.AddSingleton <DAL.Repository.IUsuarioRepository>(repUsuario);


            //Se quiser rodar com SQL
            ////**********************************////

            //var opt = SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder<LTM.DAL.Context.EFContext>(), Configuration.GetConnectionString("DefaultConnectionSql")).Options;
            //var cont = new LTM.DAL.Context.EFContext(opt);
            //var repProduto = new DAL.Repository.EFProdutoRepository(cont);
            //services.AddSingleton<DAL.Repository.IProdutoRepository>(repProduto);
            //var repUsuario = new DAL.Repository.EFUsuarioRepository(cont);
            //services.AddSingleton<DAL.Repository.IUsuarioRepository>(repUsuario);



            IConfigurationSection jwtAppSettingOptions = Configuration.GetSection("JwtIssuerOptions");
            var secretKey  = jwtAppSettingOptions["SecretKey"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options
                .TokenValidationParameters
                    = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidateLifetime         = true,
                        RequireExpirationTime    = true,
                        ValidateIssuerSigningKey = true,
                        LifetimeValidator        = JwtExpireValidator.LifetimeValidator,
                        ValidIssuer      = jwtAppSettingOptions["Issuer"],
                        ValidAudience    = jwtAppSettingOptions["Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(signingKey.ToString()))
                    };
            });
        }