public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //var client = new UserClient();
            //var result = client.Login(request, out status, out message);
            //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;
            //    }
            //}

            //create identity
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            //var identity = new ClaimsIdentity("Embedded");
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.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(identity, props);

            context.Validated(ticket);
        }
        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");

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

            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);

        }
        public void GoogleOAuth2Configuration(IAppBuilder app)
        {
            app.UseAuthSignInCookie();

            var option = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "581497791735.apps.googleusercontent.com",
                ClientSecret = "-N8rQkJ_MKbhpaxyjdVYbFpO",
            };

            app.UseGoogleAuthentication(option);

            app.Run(async context =>
                {
                    if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated)
                    {
                        var authenticationProperties = new AuthenticationProperties();
                        authenticationProperties.Dictionary.Add("access_type", "custom_accessType");
                        authenticationProperties.Dictionary.Add("approval_prompt", "custom_approval_prompt");
                        authenticationProperties.Dictionary.Add("login_hint", "custom_login_hint");

                        context.Authentication.Challenge(authenticationProperties, "Google");
                        await context.Response.WriteAsync("Unauthorized");
                    }
                });
        }
        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);
        }
Example #5
0
        protected override void AddNonceToMessage(OpenIdConnectMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var properties = new AuthenticationProperties();
            var nonce = Options.ProtocolValidator.GenerateNonce();
            properties.Dictionary.Add(
                NonceProperty, nonce);
            message.Nonce = nonce;

            //computing the hash of nonce and appending it to the cookie name
            string nonceKey = GetNonceKey(nonce);
            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure,
            };
            var nonceId = Convert.ToBase64String(Encoding.UTF8.GetBytes((Options.StateDataFormat.Protect(properties))));
            Response.Cookies.Append(
                nonceKey,
                nonceId,
                cookieOptions);
        }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (model.UserName == model.Password) //valdiate credentials there
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.UserName),
                    new Claim(ClaimTypes.Email, "user@email.com"),
                    new Claim(ClaimTypes.Role, "Administrator"),
                    new Claim("Custom", "Custom Claim Value")
                };

                var id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
                var authenticationManager = this.Request.GetOwinContext().Authentication;

                var authProperties = new AuthenticationProperties() { IsPersistent = true };

                authenticationManager.SignIn(authProperties, id);
                if (Url.IsLocalUrl(returnUrl))
                {
                    Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            return View();
        }
Example #7
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var userPasswordStore = _userPasswordStoreFactory())
            {
                var user = await userPasswordStore.FindByNameAsync(context.UserName);

                if (user == null)
                {
                    context.SetError("invalid_grant", "No user by that user name exists.");
                    return;
                }

                var passwordHash = await userPasswordStore.GetPasswordHashAsync(user);

                if (_passwordHasher.VerifyHashedPassword(passwordHash, context.Password) == PasswordVerificationResult.Failed)
                {
                    context.SetError("invalid_grant", "The password is incorrect.");
                    return;
                }

                ClaimsIdentity oauthIdentity = user.CreateIdentity(OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookiesIdentity = user.CreateIdentity(CookieAuthenticationDefaults.AuthenticationType);
                var properties = new AuthenticationProperties(new Dictionary<string, string> { { "userName", user.UserName } });
                var ticket = new AuthenticationTicket(oauthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
 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 async Task<AuthenticationTicket> ValidateTicket(IOwinRequest request, IOwinContext context, HttpClient httpClient,
            string ticket, AuthenticationProperties properties, string service)
        {
            // Now, we need to get the ticket validated
            string validateUrl = _options.CasServerUrlBase + "/validate" +
                                 "?service=" + service +
                                 "&ticket=" + Uri.EscapeDataString(ticket);

            HttpResponseMessage response = await httpClient.GetAsync(validateUrl, request.CallCancelled);

            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();


            String validatedUserName = null;
            var responseParts = responseBody.Split('\n');
            if (responseParts.Length >= 2 && responseParts[0] == "yes")
                validatedUserName = responseParts[1];

            if (!String.IsNullOrEmpty(validatedUserName))
            {
                var identity = new ClaimsIdentity(_options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", _options.AuthenticationType));
                identity.AddClaim(new Claim(ClaimTypes.Name, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", _options.AuthenticationType));

                var authenticatedContext = new CasAuthenticatedContext(context, identity, properties);

                await _options.Provider.Authenticated(authenticatedContext);

                return new AuthenticationTicket(authenticatedContext.Identity, authenticatedContext.Properties);
            }

            return new AuthenticationTicket(null, properties);
        }
        public ActionResult Login(string userName, string password)
        {
            var user = Authenticate(userName, password);

            if (user != null)
            {
                var claims = new[] { new Claim(ClaimTypes.Name, userName) };

                var identity = new ClaimsIdentity(
                    claims,
                    DefaultAuthenticationTypes.ApplicationCookie,
                    ClaimTypes.Name,
                    ClaimTypes.Role);

                foreach (var role in user.Roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }

                // Tell OWIN the identity provider, optional
                // identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));

                var properties = new AuthenticationProperties
                {
                    IsPersistent = false,
                };
                Authentication.SignIn(properties, identity);

                return RedirectToAction("index", "home");
            }

            return View("index", "Could not log you in");
        }
        public AuthenticationTicket CreateTicket(IdentityUser user, string clientId = null)
        {
            var tokenExpiration = TimeSpan.FromDays(1);

            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaim(new Claim("UserId", user.Id));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            identity.AddClaim(new Claim("role", "user"));

            foreach (var claim in user.Claims)
            {
                identity.AddClaim(new Claim(claim.ClaimType, claim.ClaimValue));
            }

            var props = new AuthenticationProperties()
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            props.Dictionary.Add("as:client_id", clientId ?? string.Empty);
            props.Dictionary.Add("userName", user.UserName);
            props.Dictionary.Add("userId", user.Id);

            var ticket = new AuthenticationTicket(identity, props);

            return ticket;
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

            var user = await _userService.Authenticate(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("role", "user"));

            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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

           user = Mapper.Map<UserModel>(await userService.FindAsync(context.UserName, context.Password));

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            else
            {
                ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));

                // Proporties
                IDictionary<string, string> prop = new Dictionary<string, string>()
                {
                    { "username", user.UserName },
                    { "id", user.Id}
                };

                // Add dictionary to auth proporties
                AuthenticationProperties proporties = new AuthenticationProperties(prop);

                AuthenticationTicket ticket = new AuthenticationTicket(identity, proporties);
                
                context.Validated(ticket);
            }

        }
        public override async Task GrantResourceOwnerCredentials
            (OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate user credentials (demo!)
            // user credentials should be stored securely (salted, iterated, hashed…)
            if (!((context.UserName == "test.test@mail.com" && context.Password == "test123")||
                (context.UserName == "jyoti.sinha@live.com" && context.Password == "test123")))
            {
                context.Rejected();
                return;
            }

            // create identity
            var id = new ClaimsIdentity("Embedded");
            id.AddClaim(new Claim("sub", context.UserName));
            id.AddClaim(new Claim("role", "user"));
            id.AddClaim(new Claim("privileges", "Admin,AccountViewer,AccountSubmit"));

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {"client_key", context.ClientId}
            });

            var ticket = new AuthenticationTicket(id, props);
            context.Validated(ticket);
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>(OAuthDefaults.OwinKeyAllowedOrigin) ?? "*";
            context.OwinContext.Response.Headers.Add(OAuthDefaults.HeaderKeyAllowedOrigin, new[] { allowedOrigin });

            if (ValidateUserNameAndPassword != null && !ValidateUserNameAndPassword(context.UserName, context.Password))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity(OAuthDefaults.TokenFormat);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(OAuthDefaults.ClaimKeySub, context.UserName));
            identity.AddClaim(new Claim(OAuthDefaults.ClaimKeySite, context.Request.Uri.Host.Split('.')[0]));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {
                         OAuthDefaults.HeaderKeyClientId, context.ClientId ?? string.Empty
                    },
                    {
                        OAuthDefaults.HeaderKeyUserName, context.UserName
                    }
                });

            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[] { "*" });

            var identity = _accountService.FindUser(context);

            if (identity == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            else
            {
                var props = new AuthenticationProperties(new Dictionary<string, string>());

                foreach (var claim in identity.Claims)
                {
                    props.Dictionary.Add(claim.Type, claim.Value);
                }

                var ticket = new AuthenticationTicket(identity, props);

                context.Validated(ticket);
            }
        }
Example #17
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var credentials = Validator.ValidateUser(context.UserName, context.Password);

            if (credentials == null)
            {
                context.Rejected();
                return;
            }

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

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {"oauth:client_id", context.ClientId}
                });

            var ticket = new AuthenticationTicket(id, props);
            context.Validated(ticket);
        }
 private IHttpActionResult IssueChallenge(AuthenticationProperties props)
 {           
     this.Request.GetOwinContext().Authentication.Challenge(
         props, 
         OAuth2Config.OAuthBearerOptions.AuthenticationType);
     return this.Unauthorized();
 }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var authenticationResult = _authenticationSerivce.AuthenticateAsync(context.UserName, context.Password).Result;
            if (!authenticationResult.IsSuccessfull)
            {
                context.SetError("invalid_grant", authenticationResult.Message);

                return Task.FromResult<object>(null);
            }

            var identity = _authenticationSerivce.CreateIdentityAsync(authenticationResult.AuthenticatedUser).Result;

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

            var ticket = new AuthenticationTicket(identity, props);

            return Task.FromResult(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);
        }
 public ActionResult GoogleLogin(string returnUrl) {
     var properties = new AuthenticationProperties {
         RedirectUri = Url.Action("GoogleLoginCallback", new {returnUrl = returnUrl})
     };
     HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");
     return new HttpUnauthorizedResult();
 }
        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);

        }
Example #23
0
        public ActionResult LogIn(AuthLogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            User user = userManager.Find(model.UserName, model.Password);
            if (user != null)
            {
                IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
                authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationProperties props = new AuthenticationProperties();
                props.IsPersistent = model.RememberMe;
                authenticationManager.SignIn(props, identity);
                if (Url.IsLocalUrl(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Question");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }

            return View();
        }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (model.UserName != model.Password) return View();

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Email, "user@email.com"),
                new Claim(ClaimTypes.Role, "Administrator"),
                new Claim("Data", "Read"),
            };

            var id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
            var authenticationManager = Request.GetOwinContext().Authentication;

            var authProperties = new AuthenticationProperties { IsPersistent = true };

            authenticationManager.SignIn(authProperties, id);

            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }
        /// <summary>
        /// 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". If the web application supports the resource owner 
        /// credentials grant type it must validate the context.Username and context.Password as appropriate. 
        /// 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. 
        /// The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers. 
        /// The default behavior is to reject this grant type. See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

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

            if (context.UserName == "Pussy" && context.Password == "Cat")
            {


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

                // 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(identity, props);
                context.Validated(ticket);
                //context.Validated(identity);
                return;
            }
            context.Rejected();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                var provider = Request.Form["provider"];
                if (provider == null)
                {
                    return;
                }

                // Request a redirect to the external login provider
                string redirectUrl = ResolveUrl(String.Format(CultureInfo.InvariantCulture, "~/Account/RegisterExternalLogin?{0}={1}&returnUrl={2}", IdentityHelper.ProviderNameKey, provider, ReturnUrl));
                var properties = new AuthenticationProperties() { RedirectUri = redirectUrl };

                // Add xsrf verification when linking accounts
                if (Context.User.Identity.IsAuthenticated)
                {
                    properties.Dictionary[IdentityHelper.XsrfKey] = Context.User.Identity.GetUserId();
                }

                Context.GetOwinContext().Authentication.Challenge(properties, provider);
                Response.StatusCode = 401;
                Response.End();
            }
        }
Example #27
0
        /// <summary>
        ///     Generate API autentication token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ApiTokenDto GenerateApiToken(User user)
        {
            Trace.WriteLine("[SecurityHelper] Generating API token.");
            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString(CultureInfo.InvariantCulture)));

            var tokenExpiration = TimeSpan.FromDays(365);
            var props = new AuthenticationProperties
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket = new AuthenticationTicket(identity, props);
            var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            if (ticket.Properties.IssuedUtc == null || ticket.Properties.ExpiresUtc == null) return null;

            var tokenResponse = new ApiTokenDto
            {
                User = _mappingEngine.Map<User, UserDto>(user),
                AccessToken = token,
                TokenType = "bearer",
                ExpiresIn = tokenExpiration.TotalSeconds.ToString(CultureInfo.InvariantCulture),
                Issued = GetUtcDateTime(ticket.Properties.IssuedUtc.Value).ToString("s"),
                Expires = GetUtcDateTime(ticket.Properties.ExpiresUtc.Value).ToString("s")
            };

            return tokenResponse;
        }
        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)
 {
     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);
 }
Example #30
0
 public override void ExecuteResult(ControllerContext context)
 {
     var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
     context.HttpContext
         .GetOwinContext()
         .Authentication
         .Challenge(properties, LoginProvider);
 }