/// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
        ///             it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
        ///             information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
        ///             included they may be added in the final TokenEndpoint call.
        ///             See also http://tools.ietf.org/html/rfc6749#section-4.5
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override Task GrantCustomExtension(OAuthGrantCustomExtensionContext context) {
            if (context.GrantType == "impersonate") {
                return GrantImpersonation(context);
            }

            return Nop;
        }
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (context.GrantType.ToLower() == "facebook")
            {
                var fbClient = new FacebookClient(context.Parameters.Get("accesstoken"));

                dynamic response = await fbClient.GetTaskAsync("me", new { fields = "email, first_name, last_name" });
                
                string id = response.id;
                string email = response.email;
                string firstname = response.first_name;
                string lastname = response.last_name;
                // place your own logic to lookup and/or create users....

                // your choice of claims...
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", $"{firstname} {lastname}"));
                identity.AddClaim(new Claim("role", id));

                await base.GrantCustomExtension(context);
                context.Validated(identity);

            }            
            return;
        }
        private static async Task GrantImpersonation(OAuthGrantCustomExtensionContext context) {
            string ticketString = context.Parameters["ticket"];
            AuthenticationTicket ticket = context.Options.AccessTokenFormat.Unprotect(ticketString);

            if (ticket == null) {
                context.SetError("invalid_grant", "The access token is invalid.");
                return;
            }

            using (var repo = ContainerConfig.Container.GetInstance<AppUserManager>()) {
                string userIdString = ticket.Identity.GetUserId();
                var currentUser = await repo.FindByIdAsync(Int32.Parse(userIdString));

                if (currentUser == null) {
                    context.SetError("invalid_grant", "The access token is invalid.");
                    return;
                }

                AppUser targetUser = await GetTargetUser(context, repo);

                if (targetUser == null || !targetUser.TrustedUsers.Contains(currentUser)) {
                    context.SetError("invalid_parameter", "The impersonation user id is invalid.");
                    return;
                }

                await ValidateIdentity(context, targetUser, repo);
            }
        }
Exemplo n.º 4
0
        public override async System.Threading.Tasks.Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if(context.GrantType.ToLower() == "facebook")
            {
                var fbClient = new FacebookClient(context.Parameters.Get("accesstoken"));
                dynamic mainDataResponse = await fbClient.GetTaskAsync("me", new { fields = "first_name, last_name, picture" });
                dynamic friendListResponse = await fbClient.GetTaskAsync("me/friends");
                var friendsResult = (IDictionary<string, object>)friendListResponse;
                var friendsData = (IEnumerable<object>)friendsResult["data"];
                var friendsIdList = new List<string>();
                foreach (var item in friendsData)
                {
                    var friend = (IDictionary<string, object>)item;
                    friendsIdList.Add((string)friend["id"]);
                }
                User user = await CreateOrUpdateUser(mainDataResponse.id, mainDataResponse.first_name, mainDataResponse.last_name, mainDataResponse.picture.data.url, friendsIdList);
                
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(_fbIdKey, mainDataResponse.id));
                identity.AddClaim(new Claim(_idKey, user.Id.ToString()));

                await base.GrantCustomExtension(context);
                context.Validated(identity);
            }
            return;
        }
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            //this is called in the authorization code grant flow.
            //here we exchange token / Windows ClaimsPrincipal into a Series5 token / ClaimsPrinicipal
            //Learn here: http://www.pluralsight.com/training/player?author=dominick-baier&name=oauthintro-m5-oauth2&mode=live&clip=9&course=oauth2-json-web-tokens-openid-connect-introduction

            context.Rejected();
            await Task.FromResult<object>(null);
        }
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (context.GrantType != "anonymous")
            {
                return;
            }

            var db = new KiwiContext();

            var protectedToken = HttpServerUtility.UrlTokenDecode(context.Parameters.Get("token"));

            if (protectedToken == null)
            {
                return;
            }

            var anonymousToken = Encoding.UTF8.GetString(MachineKey.Unprotect(protectedToken));

            var tokenArray = anonymousToken.Split('‼');

            var reportId = Int32.Parse(tokenArray[0]);
            var time = DateTime.Parse(tokenArray[1]);

            if (tokenArray.Count() != 2 && reportId != 0 && time != new DateTime())
            {
                context.SetError("invalid_grant", "This token is invalid");
                return;
            }

            if (time < DateTime.Now)
            {
                context.SetError("invalid_grant", "This token has expired");
                return;
            }

            if (await db.Reports.FindAsync(reportId) == null)
            {
                context.SetError("invalid_grant", "No report found with that ID");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Role, "Anonymous"));
            identity.AddClaim(new Claim("reportId", reportId.ToString()));
            identity.AddClaim(new Claim("is_anonymous", "true"));

            // token for reporting users should be valid for 10 minutes
            //context.Options.AccessTokenExpireTimeSpan = new TimeSpan(0, 10, 0);

            context.Validated(identity);
        }
        public override Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            var windowsPrincipal = context.OwinContext.Authentication.User as WindowsPrincipal;

            if (windowsPrincipal == null)
            {
                context.SetError("User is not a Windows user");
                return Task.FromResult(0);
            }

            var subject = SubjectGenerator.Create(windowsPrincipal, _options);
            context.Validated(subject);

            return Task.FromResult(0);
        }
 private Task ValidateCustomGrant(OAuthGrantCustomExtensionContext ctx)
 {
     if (ctx.GrantType == "urn:example:register")
     {
         if (ctx.ClientId == "alpha2")
         {
             var claims = new List<Claim>();
             claims.Add(new Claim("the-grant-type", ctx.GrantType));
             claims.Add(new Claim(ClaimsIdentity.DefaultNameClaimType, ctx.Parameters["alias"]));
             ctx.Validated(new ClaimsIdentity(claims, "Bearer"));
         }
         else
         {
             ctx.SetError("unauthorized_client");
         }
     }
     return Task.FromResult(0);
 }
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            var windowsPrincipal = context.OwinContext.Authentication.User as WindowsPrincipal;

            if (windowsPrincipal == null)
            {
                context.SetError("User is not a Windows user");
                return;
            }

            var subject = SubjectGenerator.Create(windowsPrincipal, _options);
            var transformationContext = new CustomClaimsProviderContext
            {
                WindowsPrincipal = windowsPrincipal,
                OutgoingSubject = subject
            };
            await _options.CustomClaimsProvider.TransformAsync(transformationContext);
            context.Validated(transformationContext.OutgoingSubject);
        }
Exemplo n.º 10
0
 public override Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
 {
     return(base.GrantCustomExtension(context));
 }
 public Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 12
0
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (context.Parameters["grant_type"] == "social_login" && context.Parameters["tokenOrigin"] == "facebook")
            {
                var facebookclient = new FacebookClient(context.Parameters["access_token"]);

                var parameters = new Dictionary <string, object>();
                parameters["fields"] = "id,name, email";

                dynamic result = facebookclient.Get("me", parameters);
                var     id     = result.id;
                string  name   = result.name;
                string  email  = result.email;
                if (!string.IsNullOrEmpty(email))
                {
                    ValidateUserAndProceed(name, email, context);
                }
            }

            else if (context.Parameters["grant_type"] == "social_login" && context.Parameters["tokenOrigin"] == "google")
            {
                //Later on lets move thsi in to web config.
                //Google.Apis.Plus.v1.PlusService plusService = new Google.Apis.Plus.v1.PlusService(
                //    new Google.Apis.Services.BaseClientService.Initializer()
                //    {
                //        ApiKey = "226533752513-7nuvqh2afhl1ku8krc61pn0eanrlk0tg.apps.googleusercontent.com",

                //    });

                //Google.Apis.Auth.OAuth2.Flows.IAuthorizationCodeFlow flow =
                //    new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow(new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
                //    {

                //        ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets { ClientSecret = "srjJTEk_exV0hwODWkT3s2yU", ClientId=
                //        "226533752513-k9omq9rlq9abj7dp363rmctoe736j4o8.apps.googleusercontent.com"
                //        },
                //        Scopes = new string[] { Google.Apis.Plus.v1.PlusService.Scope.UserinfoProfile, Google.Apis.Plus.v1.PlusService.Scope.UserinfoEmail }

                //    });

                //System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);

                //Google.Apis.Auth.OAuth2.Responses.TokenResponse token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse()
                //    {
                //        ExpiresInSeconds = Convert.ToInt64(context.Parameters["expires_in"]),
                //        Issued = dtDateTime.AddSeconds(Convert.ToInt64(context.Parameters["issued_at"])),
                //        RefreshToken = context.Parameters["expires_at"],
                //        TokenType = context.Parameters["token_type"]

                //    };
                //token.AccessToken = context.Parameters["access_token"];



                // Google.Apis.Auth.OAuth2.UserCredential credential = new Google.Apis.Auth.OAuth2.UserCredential(flow, "me", token);
                //bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;


                string     URL           = "https://www.googleapis.com/oauth2/v1/userinfo";
                string     urlParameters = "?access_token=" + context.Parameters["access_token"];
                HttpClient client        = new HttpClient();
                client.BaseAddress = new Uri(URL);

                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call!
                if (response.IsSuccessStatusCode)
                {
                    string userDetailsString = await response.Content.ReadAsStringAsync();

                    GoogleUserDataObject userObj = Newtonsoft.Json.JsonConvert.DeserializeObject <GoogleUserDataObject>(userDetailsString);

                    if (!string.IsNullOrEmpty(userObj.email))
                    {
                        //   token = credential.Token;
                        //   Google.Apis.Plus.v1.PeopleResource.GetRequest prgr = plusService.People.Get("me");
                        //   Google.Apis.Plus.v1.Data.Person googleUser = prgr.Execute();

                        string name  = userObj.name;
                        string email = userObj.email;
                        ValidateUserAndProceed(name, email, context);
                    }
                }
            }
        }
 private static async Task ValidateIdentity(OAuthGrantCustomExtensionContext context, AppUser user, AppUserManager repo) {
     ClaimsIdentity identity = await user.GenerateUserIdentityAsync(repo, context.Options.AuthenticationType);
     context.Validated(identity);
 }
Exemplo n.º 14
0
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (!context.GrantType.Equals("sso_token"))
            {
                context.Rejected();
            }
            else
            {
                var userName = context.Parameters["username"];
                var ssoKey   = context.Parameters["key"];
                var clientId = context.ClientId;


                var _dbContext = new ApplicationDbContext();

                var app =
                    await
                    _dbContext.Apps.FirstOrDefaultAsync(
                        a => a.ClientId == clientId && a.SsoEncryptionKey == ssoKey && a.IsTrusted);

                if (app == null)
                {
                    context.Rejected();
                    return;
                }
                var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.UserName == userName);


                if (user != null)
                {
                    var identity = new ClaimsIdentity("SidekickOAuth");

                    var clientName         = context.OwinContext.Get <string>("sidekick.client.name");
                    var clientMeta         = context.OwinContext.Get <string>("sidekick.client.meta");
                    var appId              = context.OwinContext.Get <int>("sidekick.client.appId");
                    var appName            = context.OwinContext.Get <string>("sidekick.client.appName");
                    var isTrusted          = context.OwinContext.Get <bool>("sidekick.client.istrusted");
                    var tokenExpiry        = context.OwinContext.Get <TimeSpan>("sidekick.client.tokenexpiry");
                    var refreshtokenExpiry = context.OwinContext.Get <TimeSpan>("sidekick.client.refreshTokenExpiry");
                    var scopeList          = context.OwinContext.Get <List <string> >("sidekick.client.scopes");
                    var allowedIps         = context.OwinContext.Get <string>("sidekick.client.allowedIps");
                    var claims             = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, userName),
                        new Claim(ClaimTypes.Email, user.Email),
                        new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                        new Claim(ClaimTypes.Sid, user.Id),
                        new Claim(ClaimTypes.GivenName, user.Fullname),
                        new Claim(ClaimTypes.Expiration, tokenExpiry.ToString()),
                        new Claim("sidekick.client.refreshTokenExpiry", refreshtokenExpiry.ToString()),
                        new Claim("sidekick.client.istrusted", isTrusted.ToString()),

                        new Claim("sidekick.client.name", clientName),
                        new Claim("sidekick.client.meta", clientMeta),
                        new Claim("sidekick.client.appId", appId.ToString()),
                        new Claim("sidekick.client.appName", appName),
                        new Claim("sidekick.client.allowedIps", allowedIps),
                    };



                    identity.AddClaims(claims);
                    foreach (var scope in scopeList)
                    {
                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                    }
                    context.Validated(identity);
                }
                else
                {
                    context.Rejected();
                }
            }

            //return base.GrantCustomExtension(context);
        }
Exemplo n.º 15
0
        private async Task GrantPasswordCaptcha(OAuthGrantCustomExtensionContext context)
        {
            var userManager = Global.Container.GetInstance <KeylolUserManager>();

            var idCode = context.Parameters["id_code"];
            var email  = context.Parameters["email"];
            // todo
            var        sms      = context.Parameters["sms"];
            var        userName = context.Parameters["user_name"];
            var        password = context.Parameters["password"];
            KeylolUser user;

            if (!string.IsNullOrWhiteSpace(idCode))
            {
                // 识别码登录
                user = await userManager.FindByIdCodeAsync(idCode);
            }
            else if (!string.IsNullOrWhiteSpace(email))
            {
                // 邮箱登录
                user = await userManager.FindByEmailAsync(email);
            }
            else if (!string.IsNullOrWhiteSpace(sms))
            {
                // 手机登录
                user = await userManager.FindByPhoneNumberAsync(sms);
            }
            else if (!string.IsNullOrWhiteSpace(userName))
            {
                // 用户名登录
                user = await userManager.FindByNameAsync(userName);
            }
            else
            {
                context.SetError(Errors.InvalidIdField);
                return;
            }

            if (user == null)
            {
                context.SetError(Errors.UserNonExistent);
                return;
            }
            if (await userManager.GetAccessFailedCountAsync(user.Id) > 0)
            {
                var geetest = Global.Container.GetInstance <GeetestProvider>();
                if (!await geetest.ValidateAsync(context.Parameters["geetest_challenge"],
                                                 context.Parameters["geetest_seccode"],
                                                 context.Parameters["geetest_validate"]))
                {
                    context.SetError(Errors.InvalidCaptcha);
                    return;
                }
            }
            if (await userManager.IsLockedOutAsync(user.Id))
            {
                context.SetError(Errors.AccountLockedOut);
                return;
            }
            if (!await userManager.CheckPasswordAsync(user, password))
            {
                await userManager.AccessFailedAsync(user.Id);

                context.SetError(Errors.InvalidPassword);
                return;
            }
            await userManager.ResetAccessFailedCountAsync(user.Id);

            context.Validated(await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType));
        }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
        ///             it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
        ///             information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
        ///             included they may be added in the final TokenEndpoint call.
        ///             See also http://tools.ietf.org/html/rfc6749#section-4.5
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (this.options.Events.UnknownGrantTypeReceived != null)
            {
                this.options.Logger.DebugFormat("Authenticating token request using custom grant type");

                await this.options.Events.UnknownGrantTypeReceived(new UnknownGrantTypeReceivedEventArgs(context));
            }

            await base.GrantCustomExtension(context);
        }
        private static async Task<AppUser> GetTargetUser(OAuthGrantCustomExtensionContext context, AppUserManager repo) {
            string targetUserIdString = context.Parameters["userid"];
            int targetUserId;
            Int32.TryParse(targetUserIdString, out targetUserId);

            var targetUser = await repo.FindByIdAsync(targetUserId);
            return targetUser;
        }
 public Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            try
            {
                User userDB = null;

                if (context.GrantType.ToLower().Equals("basic"))
                {
                    var email    = context.Parameters.Get("email");
                    var password = context.Parameters.Get("password");

                    if (email.NotEmpty() && password.NotEmpty())
                    {
                        if (IoC.Resolve <UserSvc>().ExistsByEmail(email))
                        {
                            userDB = await IoC.Resolve <UserSvc>().Login(email, password);
                        }
                    }
                }

                if (userDB != null)
                {
                    IoC.Resolve <UserSvc>().Save(userDB);

                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                    identity.AddClaim(new Claim(ClaimTypes.Email, userDB.Email));
                    identity.AddClaim(new Claim(ClaimTypes.PrimarySid, userDB.ID.ToString()));
                    identity.AddClaim(new Claim(ClaimTypes.Role, userDB.RoleId.ToString()));
                    identity.AddClaim(new Claim(ClaimTypes.GivenName, userDB.LastName + ", " + userDB.Name));

                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "given_name", userDB.Name
                        },
                        {
                            "email", userDB.Email
                        },
                        {
                            "id", userDB.ID.ToString()
                        },
                        {
                            "role_id", userDB.RoleId.ToString()
                        }
                    });

                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
                else
                {
                    context.SetError(((int)ErrorCodeEnum.InvalidCredentials).ToString(), ErrorCodeEnum.InvalidCredentials.EnumDescription());
                    return;
                }
            }
            catch (Exception ex)
            {
                var exception = new AppException(ex.ToString(), ex.InnerException);
                logger.Error(exception.FullDetail);
            }

            return;
        }
Exemplo n.º 20
0
 /// <summary>
 /// For custom authentication/authorizations
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task GrantCustomExtension(OAuthGrantCustomExtensionContext context) => base.GrantCustomExtension(context);
 /// <summary>
 /// Called when a request to the Token endpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
 /// it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
 /// information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
 /// included they may be added in the final TokenEndpoint call.
 /// See also http://tools.ietf.org/html/rfc6749#section-4.5
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
 {
     return OnGrantCustomExtension.Invoke(context);
 }
Exemplo n.º 22
0
        public override  Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            
            return base.GrantCustomExtension(context);

        }