Exemplo n.º 1
0
        private object CreateToken(SigningConfig signConfig, TokenConfig tokenConfig, Operator operador)
        {
            var identity  = new ClaimsIdentity(AuthExts.ToClaims(operador), tokenConfig.Type);
            var createdAt = DateTime.UtcNow;
            var expires   = createdAt + TimeSpan.FromHours(tokenConfig.Hours);

            var handler       = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = tokenConfig.Issuer,
                Audience           = tokenConfig.Audience,
                SigningCredentials = signConfig.SigningCredentials,
                Subject            = identity,
                NotBefore          = createdAt,
                Expires            = expires
            });

            var token = handler.WriteToken(securityToken);

            return(new
            {
                accessToken = token,
                expiresIn = expires,
                user = new
                {
                    id = operador.Id,
                    name = operador.Name,
                    email = operador.Email,
                    type = operador.Type.ToString().ToLower()
                }
            });
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel login, [FromServices] SigningConfig signingConfigs, [FromServices] TokenConfig tokenConfigs)
        {
            if (login == null)
            {
                NotificaErro("Login", "LoginViewModel null");
                return(Response(null));
            }
            ;

            var loginResponse = await _usuarioService.Login(login.UserName, login.Senha);

            if (!loginResponse)
            {
                return(Response(null));
            }

            var usuario = await _usuarioService.TrazerPorUserName(login.UserName);

            if (usuario == null)
            {
                NotificaErro("Login", "Usuario não encontrado");
                return(Response(null));
            }

            var genericIdentity = new GenericIdentity(usuario.UserName, usuario.UserName);
            var claimList       = new List <Claim>
            {
                new Claim("UserId", usuario.Id),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                new Claim(JwtRegisteredClaimNames.UniqueName, usuario.UserName)
            };

            ClaimsIdentity identity = new ClaimsIdentity(genericIdentity, claimList);

            DateTime dataCriacao   = DateTime.Now;
            DateTime dataExpiracao = dataCriacao + new TimeSpan(24, 0, 0);//TimeSpan.FromSeconds(tokenConfigs.Seconds);

            var handler = new JwtSecurityTokenHandler();

            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = tokenConfigs.Issuer,
                Audience           = tokenConfigs.Audience,
                SigningCredentials = signingConfigs.SigningCredentials,
                Subject            = identity,
                NotBefore          = dataCriacao,
                Expires            = dataExpiracao
            });

            var token = handler.WriteToken(securityToken);

            var response = new
            {
                created     = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                expiration  = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                accessToken = token
            };

            return(Response(response));
        }
Exemplo n.º 3
0
        private void SetupMocks()
        {
            _tokenOptions = new Mock <IOptions <TokenOptions> >();
            _tokenOptions.Setup(to => to.Value).Returns(new TokenOptions
            {
                Audience = "Testing",
                Issuer   = "Testing",
                AccessTokenExpiration  = 30,
                RefreshTokenExpiration = 60
            });

            _signingConfigurations = new SigningConfig(_testKey);

            _user = new User
            {
                Id           = 1,
                FirstName    = "Aluwani",
                LastName     = "Mathode",
                Email        = "*****@*****.**",
                PasswordHash = "123",
                Roles        = new Collection <UserRole>
                {
                    new UserRole
                    {
                        Role = new Role
                        {
                            Id   = 1,
                            Name = ApplicationRolesEnum.Common.ToString()
                        }
                    }
                }
            };
        }
Exemplo n.º 4
0
 public LoginAppService(IToken token, IUserService userService, SigningConfig signingConfig, TokenConfig tokenConfig)
 {
     _token         = token;
     _userService   = userService;
     _signingConfig = signingConfig;
     _tokenConfig   = tokenConfig;
 }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped <UsuariosRepository>();
            services.AddScoped <PromotoriasRepository>();
            services.AddScoped <OpnioesRepository>();
            services.AddScoped <CidadaosRepository>();
            services.AddScoped <PromotoresRepository>();
            services.AddScoped <AtendimentosRepository>();
            services.AddScoped <SituacaoRepository>();

            // Configurando o JWT
            #region Jwt
            var signingConfigurations = new SigningConfig();
            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfig();
            new ConfigureFromConfigurationOptions <TokenConfig>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                paramsValidation.ValidateIssuerSigningKey = true;

                paramsValidation.ValidateLifetime = true;

                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

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

            // Configurando o serviço de documentação do Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MPSP WEB API", Version = "v1"
                });
            });
        }
Exemplo n.º 6
0
 public AuthService(
     IUserRepository userRepository,
     SigningConfig signingConfig,
     TokenConfig tokenConfig
     )
 {
     _userRepository = userRepository;
     _signingConfig  = signingConfig;
     _tokenConfig    = tokenConfig;
 }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(fv =>
            {
                fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
                fv.ImplicitlyValidateChildProperties = true;
            });

            var signingConfig = new SigningConfig();

            services.AddSingleton(signingConfig);
            var tokenConfig = new TokenConfig();

            new ConfigureFromConfigurationOptions <TokenConfig>(Configuration.GetSection("TokenConfig"))
            .Configure(tokenConfig);
            services.AddSingleton(tokenConfig);

            BootStrapper.Register(services);

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime         = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = tokenConfig.Issuer,
                    ValidAudience    = tokenConfig.Audience,
                    IssuerSigningKey = signingConfig.Key,
                    ClockSkew        = TimeSpan.Zero
                };
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy(
                    "Bearer",
                    new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build()
                    );
            });
        }
Exemplo n.º 8
0
 public UserService(UserManager <User> userManager,
                    SignInManager <User> signInManager,
                    SigningConfig signingConfig,
                    JwtConfig jwtConfig,
                    MSFIdentityDbContext context)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _signingConfig = signingConfig;
     _jwtConfig     = jwtConfig;
     _context       = context;
     configuration  = ConfigurationFactory.GetConfiguration();
 }
Exemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            #region Auth Config
            var signingConfigurations = new SigningConfig();
            services.AddSingleton(signingConfigurations);

            var tokenConfig = new TokenConfig();
            new ConfigureFromConfigurationOptions <TokenConfig>(Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfig);

            services.AddSingleton(tokenConfig);
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var paramsValidation = options.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfig.Audience;
                paramsValidation.ValidIssuer      = tokenConfig.Issuer;

                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(auth =>
            {
                var jwtAuth = new AuthorizationPolicyBuilder()
                              .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                              .RequireAuthenticatedUser().Build();

                auth.AddPolicy("JwtBearer", jwtAuth);
                auth.DefaultPolicy = jwtAuth;
            });
            #endregion

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

            services.AddAutoMapper(config => Mapping.Initialize(config));

            services.AddMvc(opt => opt.CoreMvc())
            .AddJsonOptions(opt => opt.CoreJson())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors();
        }
        public static void SessionSetupResponse(
            ModelSmb2Status status,
            SigningModelSessionId sessionId,
            SigningFlagType signingFlagType,
            SessionFlags_Values sessionFlag,
            SigningConfig c)
        {
            Condition.IsTrue(State == ModelState.Connected);
            Condition.IsTrue(Config.IsServerSigningRequired == c.IsServerSigningRequired);

            SigningModelRequest sessionSetupRequest = ModelHelper.RetrieveOutstandingRequest <SigningModelRequest>(ref Request);

            if (!VerifySignature(status, sessionSetupRequest))
            {
                State = ModelState.Uninitialized;
                return;
            }

            if (sessionSetupRequest.signingFlagType == SigningFlagType.SignedFlagSet ||
                (!sessionFlag.HasFlag(SessionFlags_Values.SESSION_FLAG_IS_GUEST) &&
                 !Session_IsAnonymous &&
                 (Connection_ShouldSign || c.IsServerSigningRequired)))
            {
                ModelHelper.Log(LogType.Requirement,
                                "3.3.5.5.3: 5. Session.SigningRequired MUST be set to TRUE under the following conditions:");
                ModelHelper.Log(LogType.Requirement,
                                "\tIf the SMB2_NEGOTIATE_SIGNING_REQUIRED bit is set in the SecurityMode field of the client request.");
                ModelHelper.Log(LogType.Requirement,
                                "\tIf the SMB2_SESSION_FLAG_IS_GUEST bit is not set in the SessionFlags field " +
                                "and Session.IsAnonymous is FALSE and either Connection.ShouldSign or global RequireMessageSigning is TRUE.");

                ModelHelper.Log(LogType.TestInfo,
                                "SMB2_NEGOTIATE_SIGNING_REQUIRED is {0}set.", sessionSetupRequest.signingFlagType == SigningFlagType.SignedFlagSet ? "" : "not ");
                ModelHelper.Log(LogType.TestInfo,
                                "SMB2_SESSION_FLAG_IS_GUEST bit is {0}set.", sessionFlag.HasFlag(SessionFlags_Values.SESSION_FLAG_IS_GUEST) ? "" : "not ");
                ModelHelper.Log(LogType.TestInfo, "Session.IsAnonymous is {0}.", Session_IsAnonymous);
                ModelHelper.Log(LogType.TestInfo, "Connection.ShouldSign is {0}.", Connection_ShouldSign);
                ModelHelper.Log(LogType.TestInfo, "Global RequireMessageSigning is {0}.", c.IsServerSigningRequired);
                ModelHelper.Log(LogType.TestInfo, "So Session.SigningRequired is set to TRUE.");

                Session_SigningRequired = true;
            }

            VerifyResponseShouldSign(status, sessionSetupRequest, sessionId, signingFlagType);

            Condition.IsTrue(status == ModelSmb2Status.STATUS_SUCCESS);

            Session_IsExisted = true;
        }
Exemplo n.º 11
0
        public static IServiceCollection AddApplicationDependencies(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Subscription.Data")));

            //services.AddIdentity<User, Role>()
            //.AddEntityFrameworkStores<ApplicationDbContext>()
            //.AddDefaultTokenProviders();
            services.AddIdentity <User, Role>()
            .AddUserStore <UserStore <User, Role, ApplicationDbContext, int, IdentityUserClaim <int>, UserRole, IdentityUserLogin <int>, IdentityUserToken <int>, IdentityRoleClaim <int> > >()
            .AddRoleStore <RoleStore <Role, ApplicationDbContext, int, UserRole, IdentityRoleClaim <int> > >()
            .AddDefaultTokenProviders();

            services.AddScoped <IExceptionService, ExceptionService>();

            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <ISubscriptionTypeService, SubscriptionTypeService>();
            services.AddScoped <IBookService, BookService>();
            services.AddScoped <IUserService, UserService>();

            services.AddSingleton <ITokenHandler, Data.Security.Tokens.TokenHandler>();

            services.Configure <Subscription.Data.Security.Tokens.TokenOptions>(configuration.GetSection("TokenOptions"));
            var tokenOptions = configuration.GetSection("TokenOptions").Get <Subscription.Data.Security.Tokens.TokenOptions>();

            var signingConfigurations = new SigningConfig(tokenOptions.Secret);

            services.AddSingleton(signingConfigurations);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience,
                    IssuerSigningKey = signingConfigurations.SecurityKey,
                    ClockSkew        = TimeSpan.Zero
                };
            });

            return(services);
        }
        public static void ReadConfigReturn(SigningConfig c)
        {
            Condition.IsTrue(State == ModelState.Uninitialized);
            Condition.IsNotNull(c);

            NegotiateDialect = DialectRevision.Smb2Unknown;

            Condition.IsTrue(c.MaxSmbVersionSupported == ModelDialectRevision.Smb2002 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb21 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb30 ||
                             c.MaxSmbVersionSupported == ModelDialectRevision.Smb302);
            Config = c;

            Request = null;

            State = ModelState.Initialized;
        }
Exemplo n.º 13
0
        public TokenModel Token(LoginModel user, SigningConfig signingConfigurations
                                , TokenConfig tokenConfigurations)
        {
            try
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(user.Id.ToString(), "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString()),
                }
                    );

                DateTime CreatedDate = DateTime.Now;
                DateTime ExpiredDate = CreatedDate + TimeSpan.FromMinutes(tokenConfigurations.Minutes);
                IdentityModelEventSource.ShowPII = true;
                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = tokenConfigurations.Issuer,
                    Audience           = tokenConfigurations.Audience,
                    SigningCredentials = signingConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = CreatedDate,
                    Expires            = ExpiredDate
                });
                var token = handler.WriteToken(securityToken);

                return(new TokenModel()
                {
                    Authenticated = true,
                    Created = CreatedDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Expiration = ExpiredDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    AccessToken = token
                });
            }
            catch
            {
                return(new TokenModel {
                    Authenticated = false
                });
            }
        }
Exemplo n.º 14
0
        private void ConfigureAuthentication(IServiceCollection services)
        {
            services.AddMvcCore().AddJsonOptions(opcoes =>
            {
                opcoes.JsonSerializerOptions.IgnoreNullValues = true;
            });

            var signingConfigurations = new SigningConfig();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfig();

            new ConfigureFromConfigurationOptions <TokenConfig>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = signingConfigurations.Key;
                paramsValidation.ValidAudience            = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer              = tokenConfigurations.Issuer;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Login(
            [FromBody] LoginRequest request,
            [FromServices] SigningConfig signConfig,
            [FromServices] TokenConfig tokenConfig)
        {
            var invalidExn  = new ValidationExn("Nome de usuário ou senha está incorreto.");
            var username    = request.username.ToTrim();
            var usuarioSalt = await DbContext.Usuario
                              .Where(u => u.Login == username)
                              .Select(u => u.Chave)
                              .SingleOrDefaultAsync();

            if (usuarioSalt == null)
            {
                throw invalidExn;
            }

            var pass    = Auth.GetPassword(request.password, usuarioSalt);
            var usuario = await DbContext.Usuario
                          .Where(u => u.Login == username && u.Senha == pass)
                          .Select(u => new Operator
            {
                Id    = u.Id,
                Name  = u.Nome,
                Email = u.Email,
                Type  = (UserType)u.Tipo
            })
                          .SingleOrDefaultAsync();

            if (usuario == null)
            {
                throw invalidExn;
            }

            return(Ok(CreateToken(signConfig, tokenConfig, usuario)));
        }
Exemplo n.º 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddDbContext <RSApiContext>(
                opt => opt.UseNpgsql(
                    Configuration.GetConnectionString("conexaoPostgreSQL")
                    ));

            var signingConfig = new SigningConfig();

            services.AddSingleton(signingConfig);

            var tokenConfig = new TokenConfig();

            new ConfigureFromConfigurationOptions <TokenConfig>(Configuration.GetSection("TokenConfigs")).Configure(tokenConfig);
            services.AddSingleton(tokenConfig);

            services.AddAuthentication(authOptions => {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions => {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfig.key;
                paramsValidation.ValidAudience    = tokenConfig.audience;
                paramsValidation.ValidIssuer      = tokenConfig.issuer;

                // Validade a assinatura do token
                paramsValidation.ValidateIssuerSigningKey = true;
                // Verifica validade do token
                paramsValidation.ValidateLifetime = true;

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

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // services.AddSwaggerGen(c =>
            // {
            //     c.SwaggerDoc("v1", new OpenApiInfo { Title = "Reports System - IMD/UFRN", Version = "v1" });
            // });
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info {
                    Title = "Sistema de Relatórios - IMD/UFRN", Version = "v1"
                });
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);
            });
        }
Exemplo n.º 17
0
 public TokenHandler(IOptions <TokenOptions> tokenOptionsSnapshot, SigningConfig signingConfigurations)
 {
     _tokenOptions          = tokenOptionsSnapshot.Value;
     _signingConfigurations = signingConfigurations;
 }
Exemplo n.º 18
0
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureInjection.Database(services);
            ConfigureInjection.Services(services);
            ConfigureInjection.Repositories(services);

            var tokenConfig   = Configuration.GetSection("TokenConfig").Get <TokenConfig>();
            var signingConfig = new SigningConfig(tokenConfig);

            services.AddSingleton(tokenConfig);
            services.AddSingleton(signingConfig);

            services
            .AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options => {
                var validation = options.TokenValidationParameters;
                validation.IssuerSigningKey         = signingConfig.Key;
                validation.ValidAudience            = tokenConfig.Audience;
                validation.ValidIssuer              = tokenConfig.Issuer;
                validation.ValidateIssuerSigningKey = true;
                validation.ValidateLifetime         = true;
                validation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(options => {
                options.DefaultPolicy = new AuthorizationPolicyBuilder()
                                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            services.AddMvcCore()
            .AddJsonOptions(options => {
                options.JsonSerializerOptions.IgnoreNullValues = true;
            })
            .ConfigureApiBehaviorOptions(
                options => options.InvalidModelStateResponseFactory = ctx => {
                var errors = ctx.ModelState.Values
                             .SelectMany(v => v.Errors)
                             .Select(e => e.ErrorMessage);
                var result = new Result(EStatus.Invalid, errors);
                return(new BadRequestObjectResult(result));
            }
                );
            services.AddControllers();
            services.AddSwaggerGen(options => {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Version     = "v1",
                    Title       = "Identity Server API",
                    Description = "Identity Server",
                    Contact     = new OpenApiContact {
                        Name  = "Paulo Ricardo Busch",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://www.dynsoftware.net")
                    }
                });
            });
        }
Exemplo n.º 19
0
        public object Post(
            [FromBody] Usuarios usuario,
            [FromServices] SigningConfig signingConfigurations,
            [FromServices] TokenConfig tokenConfigurations)
        {
            Usuarios usuarioBase = null;

            if (usuario != null && !String.IsNullOrWhiteSpace(usuario.Login))
            {
                //Seleciona o usuário
                usuarioBase = _usuarioRepository.LoginUsuario(usuario);
            }

            if (usuarioBase != null)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(usuario.Login, "Login"),
                    new[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, usuario.Login)
                }
                    );

                DateTime dataCriacao   = DateTime.Now;
                DateTime dataExpiracao = dataCriacao +
                                         TimeSpan.FromSeconds(tokenConfigurations.Seconds);

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = tokenConfigurations.Issuer,
                    Audience           = tokenConfigurations.Audience,
                    SigningCredentials = signingConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = dataCriacao,
                    Expires            = dataExpiracao
                });
                var token = handler.WriteToken(securityToken);

                return(new
                {
                    authenticated = true,
                    criado = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                    expiracao = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                    accessToken = token,
                    message = "OK",
                    UserID = usuarioBase.ID,
                    UserName = usuarioBase.Nome,
                    Login = usuarioBase.Login,
                });
            }
            else
            {
                return(new
                {
                    authenticated = false,
                    message = "Falha ao autenticar"
                });
            }
        }
        public object Post(
            [FromBody] Usuario usuario,
            [FromServices] SigningConfig signingConfigurations,
            [FromServices] TokenConfig tokenConfigurations)
        {
            bool credenciaisValidas = false;

            if (usuario != null && !String.IsNullOrWhiteSpace(usuario.login))
            {
                try {
                    var usuarioBase = _context.Usuarios.Where(u => u.login == usuario.login).First();
                    credenciaisValidas = (usuarioBase != null && usuario.login == usuarioBase.login && usuario.senha == usuarioBase.senha);
                } catch {
                    return(new { authenticated = false, message = "Falha na autenticação! Usuário não encontrado " });
                }
            }

            if (credenciaisValidas)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(usuario.login, "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, usuario.login)
                }
                    );

                DateTime dataCriacao   = DateTime.Now;
                DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(tokenConfigurations.seconds);

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = tokenConfigurations.issuer,
                    Audience           = tokenConfigurations.audience,
                    SigningCredentials = signingConfigurations.signingCredentials,
                    Subject            = identity,
                    NotBefore          = dataCriacao,
                    Expires            = dataExpiracao
                });

                var usuarioBase = _context.Usuarios.Where(u => u.login == usuario.login).First();

                var token = handler.WriteToken(securityToken);

                return(new
                {
                    authenticated = true,
                    user = new NewClass(usuarioBase.nome, usuarioBase.login, usuarioBase.id, usuarioBase.idPerfil),
                    created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                    expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                    accessToken = token,
                    message = "Login Realizado com Sucesso!"
                });
            }
            else
            {
                return(new {
                    authenticated = false, message = "Falha na auteticação! Senha incorreta ou usuário não informado."
                });
            }
        }
        public static void NegotiateResponse(ModelSmb2Status status, SigningEnabledType signingEnabledType, SigningRequiredType signingRequiredType, SigningConfig c)
        {
            Condition.IsTrue(State == ModelState.Connected);

            SigningModelRequest negotiateRequest = ModelHelper.RetrieveOutstandingRequest <SigningModelRequest>(ref Request);

            if (negotiateRequest.signingFlagType == SigningFlagType.SignedFlagSet)
            {
                ModelHelper.Log(LogType.Requirement,
                                "3.3.5.2.4: If the SMB2 Header of the SMB2 NEGOTIATE request has the SMB2_FLAGS_SIGNED bit set in the Flags field, " +
                                "the server MUST fail the request with STATUS_INVALID_PARAMETER.");
                ModelHelper.Log(LogType.TestInfo, "SMB2_FLAGS_SIGNED bit in the NEGOTIATE request is set.");
                ModelHelper.Log(LogType.TestTag, TestTag.UnexpectedFields);
                Condition.IsTrue(status == ModelSmb2Status.STATUS_INVALID_PARAMETER);
                State = ModelState.Uninitialized;

                return;
            }

            if (negotiateRequest.signingRequiredType == SigningRequiredType.SigningRequiredSet)
            {
                ModelHelper.Log(LogType.Requirement,
                                "3.3.5.4: If SMB2_NEGOTIATE_SIGNING_REQUIRED is set in SecurityMode, the server MUST set Connection.ShouldSign to TRUE.");
                ModelHelper.Log(LogType.TestInfo, "Connection.ShouldSign is set to TRUE.");
                Connection_ShouldSign = true;
            }

            ModelHelper.Log(LogType.Requirement, "3.3.5.4: SecurityMode MUST have the SMB2_NEGOTIATE_SIGNING_ENABLED bit set.");
            Condition.IsTrue(signingEnabledType == SigningEnabledType.SigningEnabledSet);

            Condition.IsTrue(Config.IsServerSigningRequired == c.IsServerSigningRequired);
            if (Config.IsServerSigningRequired)
            {
                ModelHelper.Log(LogType.Requirement,
                                "3.3.5.4: If RequireMessageSigning is TRUE, the server MUST also set SMB2_NEGOTIATE_SIGNING_REQUIRED in the SecurityMode field.");
                ModelHelper.Log(LogType.TestInfo, "RequireMessageSigning is TRUE.");
                Condition.IsTrue(signingRequiredType == SigningRequiredType.SigningRequiredSet);
            }

            Condition.IsTrue(status == ModelSmb2Status.STATUS_SUCCESS);
        }
Exemplo n.º 22
0
 public Token(SigningConfig signingConfig, TokenConfig tokenConfig)
 {
     _signingConfig = signingConfig;
     _tokenConfig   = tokenConfig;
 }
Exemplo n.º 23
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <IMSFDbContext, MSFDbContext>(options =>
                                                                options.UseSqlServer(Configuration.GetConnectionString("MSF_DEV")));

            services.AddDbContext <MSFIdentityDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("MSF_DEV")));

            services.AddIdentity <User, Role>(options => {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 5;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <MSFIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddTransient <IUnitOfWork, UnitOfWork>();

            services.AddTransient <IUserService, UserService>();

            services.AddTransient <IRoleService, RoleService>();

            services.AddTransient <ICategoryService, CategoryService>();

            services.AddTransient <IProviderService, ProviderService>();

            services.AddTransient <IStateService, StateService>();

            services.AddTransient <IShopService, ShopService>();

            services.AddTransient <IWorkCenterService, WorkCenterService>();

            services.AddTransient <IWorkCenterControlService, WorkCenterControlService>();

            services.AddTransient <IProductService, ProductService>();

            services.AddTransient <IStockService, StockService>();

            services.AddTransient <IOperationService, OperationService>();

            var signingConfig = new SigningConfig();

            services.AddSingleton(signingConfig);

            var jwtConfig = new JwtConfig();

            new ConfigureFromConfigurationOptions <JwtConfig>(
                Configuration.GetSection("JwtConfig")
                ).Configure(jwtConfig);

            services.AddSingleton(jwtConfig);

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = jwtConfig.Audience,
                    ValidIssuer      = jwtConfig.Issuer,
                    IssuerSigningKey = signingConfig.Key,
                    ClockSkew        = TimeSpan.Zero
                };
            });

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

            services.AddCors();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.ConfigureProblemDetailsModelState();
        }
Exemplo n.º 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Security

            var signingConfigurations = new SigningConfig();
            services.AddSingleton(signingConfigurations);

            var tokenConfig = new TokenConfig();

            new ConfigureFromConfigurationOptions <TokenConfig>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfig);

            services.AddSingleton(tokenConfig);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfig.Audience;
                paramsValidation.ValidIssuer      = tokenConfig.Issuer;

                // Validates the signing of a received token
                paramsValidation.ValidateIssuerSigningKey = true;

                // Checks if a received token is still valid
                paramsValidation.ValidateLifetime = true;

                // Tolerance time for the expiration of a token (used in case
                // of time synchronization problems between different
                // computers involved in the communication process)
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            // Enables the use of the token as a means of
            // authorizing access to this project's resources
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy(AuthorizationNameOptions.Bearer, new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            #endregion Security

            #region CORS

            services.AddCors(o => o.AddPolicy("EnablingCors", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            #endregion CORS

            services.AddMvc(options =>
            {
                options.RespectBrowserAcceptHeader = true;
                options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("text/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddApiVersioning(options => options.ApiVersionReader = new HeaderApiVersionReader("api-version"));

            #region Swagger

            _ = services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(
                    "v1",
                    new OpenApiInfo
                {
                    Title       = "Divulgação de ONG's",
                    Version     = "v1",
                    Description = "API Rest desenvolvida em ASPNET Core 2.2",
                    Contact     = new OpenApiContact
                    {
                        Name = "Marcelo Ribeiro de Albuquerque",
                        Url  = new Uri("https://github.com/openid3as")
                    }
                });
                c.CustomSchemaIds(x => x.FullName);
            });

            #endregion Swagger

            services.AddDependencyInjections(Configuration);
        }