private Task <ClaimsIdentity> GetIdentity(CheckAppContext context, string username, string password, string oauth_id)
        {
            var userRepo = new UserRepository(context);
            var isAuth   = userRepo.AuthenticateUser(username, password);
            var isFbAuth = userRepo.AuthenticateFBUser(oauth_id);

            if (isAuth || isFbAuth)
            {
                return(Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { })));
            }

            // Credentials are invalid, or account doesn't exist
            return(Task.FromResult <ClaimsIdentity>(null));
        }
        private async Task GenerateToken(HttpContext context, CheckAppContext dbcontext)
        {
            var oauth_id = context.Request.Form["oauth_id"];
            var username = context.Request.Form["username"];
            var password = context.Request.Form["password"];

            var identity = await _options.IdentityResolver(dbcontext, username, password, oauth_id);

            if (identity == null)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Usuário ou senha inválidos.");

                return;
            }

            var now = DateTime.UtcNow;

            // Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims.
            // You can add other claims here, if you want:
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, (string.IsNullOrEmpty(username) ? oauth_id : username)),
                new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64)
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var response   = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
        }
        public Task Invoke(HttpContext context, CheckAppContext dbcontext)
        {
            // If the request path doesn't match, skip
            if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
            {
                return(_next(context));
            }

            // Request must be POST with Content-Type: application/x-www-form-urlencoded
            if (!context.Request.Method.Equals("POST") ||
                !context.Request.HasFormContentType)
            {
                context.Response.StatusCode = 400;
                return(context.Response.WriteAsync("Bad request."));
            }

            _logger.LogInformation("Handling request: " + context.Request.Path);

            return(GenerateToken(context, dbcontext));
        }
 public LoginController(CheckAppContext context)
 {
     _context = context;
 }
 public AgendaController(CheckAppContext context)
 {
     _context = context;
 }
Beispiel #6
0
 public AppointmentTypeController(CheckAppContext context)
 {
     _context = context;
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CheckAppContext context)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var secretKey = env.IsDevelopment() ? "mysupersecretkey!@1234" : Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");

            _key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var tokenValidationParameters = new TokenValidationParameters
            {
                IssuerSigningKey         = _key,
                ValidAudience            = env.IsDevelopment() ? "localhost" : TokenAudience,
                ValidateAudience         = true,
                ValidIssuer              = env.IsDevelopment() ? "localhost" : TokenIssuer,
                ValidateIssuer           = true,
                ValidateIssuerSigningKey = true,
                ValidateLifetime         = false,
                ClockSkew = TimeSpan.Zero
            };

            // The secret key every token will be signed with.
            // Keep this safe on the server!
            var signingCredentials = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256);

            app.UseSimpleTokenProvider(new TokenProviderOptions
            {
                Path               = "/token",
                Audience           = env.IsDevelopment() ? "localhost" : TokenAudience,
                Issuer             = env.IsDevelopment() ? "localhost" : TokenIssuer,
                SigningCredentials = signingCredentials,
                IdentityResolver   = GetIdentity
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AuthenticationScheme  = "Cookie",
                CookieName            = "access_token",
                TicketDataFormat      = new CustomJwtDataFormat(SecurityAlgorithms.HmacSha256, tokenValidationParameters)
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            ConfigureRoutes(app);

            app.UseDeveloperExceptionPage();

            DbInitializer.Initialize(context);
        }