public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            // We need the token service to add the below header when the provider issues the token. This code adds a 
            // response header and specifies a URL. This is the same port where our client application is running. It's 
            // the same port we granted access to in the angular product controller. 
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:56077" });

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (context.Request.Headers["devicetoken"] != null)
            {
                if (user.DeviceToken != context.Request.Headers["devicetoken"])
                {
                    user.DeviceToken = context.Request.Headers["devicetoken"];
                    userManager.Update(user);
                }
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Ejemplo n.º 3
0
        // Called when a request to the Token endpoint arrives with a "grant_type" of "password".
        // This occurs when the user has provided name and password credentials directly
        // into the client application's user interface, and the client application is using
        // those to acquire an "access_token" and optional "refresh_token". 
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var userManager = context.OwinContext.GetUserManager<GbmonoUserManager>();

            // lookup user by user name and password
            GbmonoUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "用户名或密码不正确。");
                return;
            }

            // create user identity for Bearer token
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            // create user identity for cookie
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            // create properties, user name or other extra information
            AuthenticationProperties properties = CreateProperties(user);

            // initialize a new instance of the Microsoft.Owin.Security.AuthenticationTicket
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            // call the context.Validated(ticket) to tell the OAuth server to protect the ticket as an access token and send it out in JSON payload.
            // to issue an access token the context.Validated must be called with a new ticket containing the claims about the resource owner
            // which should be associated with the access token.
            context.Validated(ticket);

            // Signs the cookie identity so it can send the authentication cookie.
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var  allowedOrigin = "*";
            ApplicationUser appUser = null;

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            using (AuthRepository _repo = new AuthRepository())
            {
                 appUser = await _repo.FindUser(context.UserName, context.Password);

                if (appUser == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            identity.AddClaim(new Claim("PSK", appUser.PSK));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserManager<IdentityUser> userManager = _userManagerFactory())
            {
                try
                {
                    IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }

                    ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                        context.Options.AuthenticationType);
                    ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                        CookieAuthenticationDefaults.AuthenticationType);
                    AuthenticationProperties properties = CreateProperties(user.UserName, user.Roles.First().Role.Name);
                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }
                catch (Exception)
                {
                    
                    throw;
                }
                
            }
        }
        public string Authenticate(string Email, string Password)
        {
            AuthenticateService service = new AuthenticateService(_container);

            if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            {
                var user = service.Authenticate(Email, Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity = new ClaimsIdentity("Bearer");
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return token;
                }
            }

            return "false";
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            //List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            //AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value)));
            string role = "";
            if (oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).Any())
            {
                role = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).First().Value;
            }
            AuthenticationProperties properties = CreateProperties(user.UserName, role);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
            oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
            oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));
           
            var ticket = new AuthenticationTicket(oAuthIdentity, null);
            
            context.Validated(ticket);
           
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.IsApproved)
            {
                context.SetError("user_not_approved", "User is not approved. Please contact administrator.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public async override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //On créer le usermanager
            var userManager = context.OwinContext.GetUserManager<UserManager<MyUser>> ();

            //On verifie le login et mot de passe
            var user = await userManager.FindAsync(context.UserName, context.Password);


            if(user == null)
            {
                //si user n'existe pas on envoie un message d'erreur
                context.Rejected();
                context.SetError("invalidate_grant", "Le login ou le mot de passe est incorrect");
                return;
            }

            //On créer un id unique
            var id = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
            //on créer le token complet
            var ticket = new AuthenticationTicket(id, null);
            //on le valide et il est renvoyer à "l'utilisateur"
            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "as:client_id", context.ClientId ?? string.Empty
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        /// <summary>
        /// The GrantResourceOwnerCredentials method defines the custom validation scheme for user credentials.
        /// </summary>
        /// <param name="context">OAuthGrantResourceOwnerCredentials context parameter</param>
        /// <returns>The Task that completes the request.</returns>        
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Get the Endpoint of the web service for user credential validation
            string url = WebConfigurationManager.AppSettings[Constants.Authentication.WebServiceKey];

            // Call the web service
            AuthenticateUserRequestData requestData = new AuthenticateUserRequestData();
            requestData.UserName = context.UserName;
            requestData.ApiKey = context.Password;
            requestData.AnetAccountType = 'M';
            ANetApiWebService authWS = new ANetApiWebService();
            authWS.Url = url;
            AuthenticateUserResponseData authenticationResponse = authWS.AuthenticateUser(requestData);

            if (!authenticationResponse.Successful)
            {
                // No user with userName/password exists.
                context.SetError(Constants.Authentication.OAuthErrorType, Constants.Authentication.OAuthErrorMessage);
                return;
            }

            // Generate the claims for the validated user
            ClaimsIdentity oauthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType, context.UserName, "User");
            ClaimsIdentity cookiesIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType, context.UserName, "User");

            AuthenticationProperties properties = CreateProperties(context.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oauthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        } 
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            try
            {
                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                   OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                    CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (InvalidOperationException e)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect. This should not happen");
                return;
            }
        }
Ejemplo n.º 14
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     IFormCollection formCollection = await context.Request.ReadFormAsync();
     CaptchaData captcha = new CaptchaData()
     {
         CaptchaChallenge = context.UserName,
         CaptchaResponse = context.Password,
         UserHostAddress = context.Request.LocalIpAddress,
         ClientId = context.ClientId
     };
     CaptchaOutput captchaOutput = await this.ValidateCaptcha(captcha);
     if (captchaOutput == null || !captchaOutput.Status)
     {
         context.SetError("invalid_captcha", "Mã bảo vệ chưa đúng, bạn vui lòng nhập lại!");
     }
     else
     {
         ApplicationUserManager userManager = OwinContextExtensions.GetUserManager<ApplicationUserManager>(context.OwinContext);
         ApplicationUser user = await userManager.FindAsync("e7c44459-837c-45f2-b125-2b639d84ea45", "abcd@1234A");
         ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync((UserManager<ApplicationUser>)userManager, "Bearer");
         ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync((UserManager<ApplicationUser>)userManager, "Cookies");
         AuthenticationProperties properties = new AuthenticationProperties();
         properties.Dictionary.Add(new KeyValuePair<string, string>("client_id", captchaOutput.ClientId));
         AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
         context.Validated(ticket);
         context.Request.Context.Authentication.SignIn(cookiesIdentity);
     }
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://hawkwareapps.com" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "*" });
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, X-Requested-With" });

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);


            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://simpleloginform.azurewebsites.net" });
            FirstName = user.FirstName;
            LastName = user.LastName;
            if (user == null)
            {
                context.SetError("invalid_grant", "Le nom d'utilisateur ou le mot de passe est incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            UserAccount user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            string fullName = user.FirstName;

            if (!string.IsNullOrEmpty(user.LastName))
            {
                fullName = fullName + " " + user.LastName;
            }
            AuthenticationProperties properties = CreateProperties(user.UserName, fullName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);

            oAuthIdentity.AddClaims(new List<Claim> {
             new Claim(ClaimTypes.NameIdentifier, fullName),
              new Claim (ClaimTypes.Name, fullName)
            });

            context.Request.Context.Authentication.SignIn(properties, new ClaimsIdentity[] { cookiesIdentity, oAuthIdentity });
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            

            //CORS
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //CORS

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            //next line added from:
            //http://stackoverflow.com/questions/26046441/current-user-in-owin-authentication
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            // Dummy check here, you need to do your DB checks against membership system http://bit.ly/SPAAuthCode
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                //return;
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity("JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

            var props =
                new AuthenticationProperties(
                    new Dictionary<string, string>
                        {
                            {
                                "audience",
                                context.ClientId ?? string.Empty
                            }
                        });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            IdentityUser user;
            using (var _repo = new AuthRepository())
            {
                user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("userId", user.Id));

            if (user.Id == "c417fc8e-5bae-410f-b2ee-463afe2fdeaa")
                identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "userId", user.Id
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "El nombre de usuario o la contraseña no son correctos.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            new LogsController().AddLogLogin(LogsController.LOGIN, "ApplicationUser", user);


            String role = "";
            IList<String> roles = userManager.GetRoles(user.Id);
            foreach (String obj in roles)
            {
                role += obj;
            }
            
            AuthenticationProperties properties = CreateProperties(user.UserName, role);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Ejemplo n.º 22
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            if (context.UserName != "*****@*****.**" || context.Password != "%baG7cadence")
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var claims = new List<Claim>();
            //claims.Add(new Claim(ClaimTypes., context.UserName));

            var data = await context.Request.ReadFormAsync();

            var identity = new ClaimsIdentity("JWT");

            //identity.AddClaims(claims);

            int daysSignedIn = 14;
            context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromDays(daysSignedIn);

            var ticket = new AuthenticationTicket(identity, null);
            context.Validated(ticket);
        }
Ejemplo n.º 23
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
Ejemplo n.º 24
0
        //Taking UserName and Password as inputs and validated them against our ASP.NET Identity System
        //if credential is valid, then generate an identity for this logged in user.
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = context.OwinContext.GetUserManager<TRAPUserManager>();

            User user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "User did not confirm email.");
            //    return;
            //}

            ClaimsIdentity authIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
            List<Claim> roles = authIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value)));

            //AuthenticationTicket contains user identity information and authentication state
            var authTicket = new AuthenticationTicket(authIdentity, properties);

            context.Validated(authTicket);

        }
Ejemplo n.º 25
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var user = userRepository.Get(w => w.UserName == context.UserName && w.Password == context.Password);
            
            //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            ClaimsIdentity cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            if (user.Roles.Count() > 0)
            {
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Roles.FirstOrDefault().Name));
            }

            //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
            //   OAuthDefaults.AuthenticationType);
            //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
            //    CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
        /// <summary>
        /// oAuth Resource Password Login Flow
		/// 1. Checks the password with the Identity API
		/// 2. Create a user identity for the bearer token
		/// 3. Create a user identity for the cookie
		/// 4. Calls the context.Validated(ticket) to tell the oAuth2 server to protect the ticket as an access token and send it out in JSON payload
		/// 5. Signs the cookie identity so it can send the authentication cookie
        /// </summary>
        /// <param name="context">The authorization context</param>
		/// <returns>Task</returns>		
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (ApplicationUserManager userManager = _userManagerFactory())
            {
                UserProfile user = await userManager.FindAsync(context.UserName, context.Password);
                
                if (user == null)
                {
                    context.SetError("invalid_grant", "Invalid user or password");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);

                var justCreatedIdentity = await userManager.FindByNameAsync(user.UserName);
                var roles = await userManager.GetRolesAsync(justCreatedIdentity.Id);

                AuthenticationProperties properties = CreateProperties(user.UserName, roles.ToArray(), user.EmailConfirmed);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                                
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
Ejemplo n.º 27
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
                new[] { ConfigurationManager.AppSettings["internal:origins"] });

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
 /// <summary>
 ///  验证用户名与密码 [Resource Owner Password Credentials Grant[username与password]|grant_type=password&username=irving&password=654321]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     //validate user credentials (验证用户名与密码)  should be stored securely (salted, hashed, iterated) 
     var userValid = await _accountService.ValidateUserNameAuthorizationPwdAsync(context.UserName, context.Password);
     if (!userValid)
     {
         //context.Rejected();
         context.SetError(AbpConstants.AccessDenied, AbpConstants.AccessDeniedErrorDescription);
         return;
     }
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());
     context.Validated(ticket);
     /*
     //create identity
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     claimsIdentity.AddClaim(new Claim("sub", context.UserName));
     claimsIdentity.AddClaim(new Claim("role", "user"));
     // create metadata to pass on to refresh token provider
     var props = new AuthenticationProperties(new Dictionary<string, string>
                     {
                         {"as:client_id", context.ClientId }
                     });
     var ticket = new AuthenticationTicket(claimsIdentity, props);
     context.Validated(ticket);
     */
 }
        //Taking UserName and Password as inputs and validated them against our ASP.NET Identity System
        //if credential is valid, then generate an identity for this logged in user.
        //
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = context.OwinContext.GetUserManager<TRAPUserManager>();

            User user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            //if (!user.EmailConfirmed)
            //{
            //    context.SetError("invalid_grant", "User did not confirm email.");
            //    return;
            //}

            ClaimsIdentity authIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

            //AuthenticationTicket contains user identity information and authentication state
            var authTicket = new AuthenticationTicket(authIdentity, null);

            context.Validated(authTicket);

        }
Ejemplo n.º 30
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            try
            {
                bool registradoEnSalasCuna = false;
                bool logueadoEnCidi        = false;

                UsuarioCidiDto usuarioCidi = UsuarioCidiFactory.ValidarUsuarioCidi();

                if (usuarioCidi != null)
                {
                    logueadoEnCidi = true;
                    LoguinCidiQuery query = new LoguinCidiQuery
                    {
                        Cuil = usuarioCidi.Cuil
                    };

                    QueryDispatcher       _QueryDispatcher = ServiceLocator.Current.GetInstance <QueryDispatcher>();
                    LoguinCidiQueryResult queryResult      = _QueryDispatcher.Dispatch <LoguinCidiQuery, LoguinCidiQueryResult>(query);

                    if (queryResult.UsuarioDto != null && queryResult.UsuarioDto.Id != 0)
                    {
                        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                        queryResult.UsuarioDto.Apellido = usuarioCidi.Apellido;
                        queryResult.UsuarioDto.Nombre   = usuarioCidi.Nombre;

                        Claim usuarioClimb = new Claim("User", new JavaScriptSerializer().Serialize(queryResult.UsuarioDto));
                        identity.AddClaim(new Claim(ClaimTypes.Name, usuarioCidi.Cuil.ToString()));
                        identity.AddClaim(usuarioClimb);
                        UrlCidiQueryResult urlsCidiResult = _QueryDispatcher.Dispatch <UrlCidiQuery, UrlCidiQueryResult>(null);

                        //**//

                        IDictionary <string, string> data = new Dictionary <string, string>
                        {
                            //{ "Paginas", JsonConvert.SerializeObject(queryResult.FuncionalidadesDto) },
                            { "User", JsonConvert.SerializeObject(queryResult.UsuarioDto) },
                            { "UrlCidi", urlsCidiResult.UrlCidi },
                            { "UrlCerrarSesionCidi", urlsCidiResult.UrlCidiLogout },
                            { "UrlInicarSesionCidi", urlsCidiResult.UrlCidiLogin },
                            { "as:client_id", context.ClientId == null ? string.Empty : context.ClientId }
                        };
                        AuthenticationProperties properties = new AuthenticationProperties(data);

                        Microsoft.Owin.Security.AuthenticationTicket ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, properties);

                        context.Validated(ticket);

                        registradoEnSalasCuna = true;
                    }
                }

                if (!logueadoEnCidi)
                {
                    //El usuario no está logueado a través de CIDI.
                    context.SetError("NO_AUTENTICADO_EN_CIDI", "");
                    context.Response.ReasonPhrase = "NO_AUTENTICADO_EN_CIDI";
                }
                else if (!registradoEnSalasCuna)
                {
                    //El usuario está logueado a través CIDI pero no se encuentra registrado en Salas Cuna.
                    context.SetError("NO_REGISTRADO_EN_SALAS_CUNA", "");
                    //context.
                    context.Response.ReasonPhrase = "NO_REGISTRADO_EN_SALAS_CUNA";
                }
            }
            catch (Exception e)
            {
                context.SetError("Server error", e.StackTrace);
                context.Rejected();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //enable cors bang tay
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (UserManager<IdentityUser> userManager = _userManagerFactory())
            //using (var ctx = new LeaveAnnualContext())
            {
                IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
                //var user = await ctx.Accounts.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                //ClaimsIdentity oAuthIdentity = await ctx.Accounts.Crea
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }