예제 #1
0
        /// <summary>
        /// 执行授权
        /// </summary>
        /// <returns></returns>
        public bool Grant(bool takeAll, params GrantCodeRight[] rights)
        {
            OAuthApp app = OAuthAppCache.Instance.Find(it => it.APP_CODE.Equals(this._appCode));

            if (app == null)
            {
                Alert("未注册的应用");
                return(false);
            }
            GrantScope[] scope = ScopeCache.Instance.FindAll(this._scope);
            if (scope == null || scope.Length <= 0)
            {
                Alert("未定义的授权类型");
                return(false);
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByCode(this._userCode);

            if (user == null)
            {
                Alert("用户信息加载失败");
                return(false);
            }
            if (CheckAlreadyAuth(app.APP_ID, user.UserId))
            {
                return(true);
            }
            if (takeAll && (rights == null || rights.Length <= 0))
            {
                var temp = ScopeRightProvider.GetScopeRights(this._scope);
                rights = new GrantCodeRight[temp.Count];
                for (int i = 0; i < rights.Length; i++)
                {
                    rights[i] = new GrantCodeRight
                    {
                        RightId   = temp[i].Right_Id,
                        RightType = temp[i].Right_Type
                    };
                }
            }
            this.Auth_Code = Guid.NewGuid().ToString("N");
            Tauth_Code daCode = new Tauth_Code();

            daCode.App_Id      = app.APP_ID;
            daCode.Expire_Time = DateTime.Now.AddMinutes(5);
            daCode.Grant_Code  = this.Auth_Code;
            daCode.Scope_Id    = scope.FirstOrDefault().SCOPE_ID;
            daCode.User_Id     = user.UserId;
            daCode.Device_Id   = this._device_id;
            if (rights != null && rights.Length > 0)
            {
                daCode.Right_Json = Javirs.Common.Json.JsonSerializer.JsonSerialize(rights);
            }
            if (!daCode.Insert())
            {
                Alert("授权失败,请重试!");
                return(false);
            }
            return(true);
        }
예제 #2
0
 public override Task <GrantResponseDTO> GrantByToken(GrantByTokenRequestDTO request, ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         GrantResponseDTO response = new GrantResponseDTO();
         UserToken token = UserToken.FromCipherToken(request.Token);
         if (token == null)
         {
             response.RetCode = "0400";
             response.RetMsg = "无效的token";
             return response;
         }
         OAuthApp app = OAuthAppCache.Get(request.Appid);
         if (app == null)
         {
             response.RetCode = "0400";
             response.RetMsg = "无效的应用id";
             return response;
         }
         if (app.Id != token.AppId)
         {
             response.RetCode = "0403";
             response.RetMsg = "无效的token";
             return response;
         }
         CodePrivilege[] privileges = null;
         if (request.Grants != null && request.Grants.Count > 0)
         {
             privileges = new CodePrivilege[request.Grants.Count];
             for (int i = 0; i < request.Grants.Count; i++)
             {
                 privileges[i] = new CodePrivilege {
                     Id = request.Grants[i].Id, Type = request.Grants[i].Type
                 };
             }
         }
         GrantTokenPrivilegeProvider grant = new GrantTokenPrivilegeProvider(app.Appid, token.UserId, request.Scopes, request.Client.DeviceId);
         if (!grant.Grant(request.GrantAll, privileges))
         {
             response.RetCode = "0500";
             response.RetMsg = "授权失败,请重试";
             return response;
         }
         response.RetCode = "0000";
         response.RetMsg = "ok";
         response.Data = new GrantResponseDTO.Types.Result
         {
             Code = grant.Auth_Code
         };
         return response;
     }));
 }
예제 #3
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;

            campaignId = context.Parameters.Get("campaign_id");
            vendorId   = context.Parameters.Get("vendor_id");
            escape     = context.Parameters.Get("escape");

            parameters = context.Parameters;

            Guid appId;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null || !Guid.TryParse(clientId, out appId))
            {
                context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
                context.Rejected();

                return;
            }
            try
            {
                authService = new OAuthAppDataProvider();
                app         = authService.FindApp();
                if (appId == app.AppId && clientSecret == app.AppSecretHash)
                {
                    context.OwinContext.Set("oauth:client", app);
                    context.Validated(clientId);
                }
                else
                {
                    // Client could not be validated.
                    context.SetError("invalid_client", "Client credentials are invalid.");
                    context.Rejected();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                context.SetError("server_error");
                context.Rejected();
            }

            return;
        }
예제 #4
0
        /// <summary>
        /// 解密OpenID
        /// </summary>
        /// <param name="open_id"></param>
        /// <param name="userId"></param>
        /// <param name="appid"></param>
        /// <returns></returns>
        public static bool DecryptOpenId(string open_id, out int userId, out int appid)
        {
            string tokenSecret = UserToken.SECRET;
            string enc_uuid;

            DesDecrypt(open_id, tokenSecret, out enc_uuid);
            var    array       = enc_uuid.Split('_');
            int    lambdaAppid = appid = Convert.ToInt32(array[0]);
            var    app         = OAuthApp.GetOAuthApp(lambdaAppid);
            string plain_uid;

            DesDecrypt(array[1], app.UID_Encrypt_Key, out plain_uid);
            userId = Convert.ToInt32(plain_uid);
            return(true);
        }
예제 #5
0
 public override Task <GrantResponseDTO> GrantByAccount(GrantByAccountRequestDTO request, ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         var response = new GrantResponseDTO();
         OAuthApp app = OAuthAppCache.Get(request.Appid);
         List <Scope> scope = ScopeCache.Get(request.Scopes.Split(','));
         if (app == null)
         {
             response.RetCode = "0400";
             response.RetMsg = "无效的应用id";
             return response;
         }
         string ip = context.GetHttpContext().Request.Headers["X-FORWARD-IP"];
         LoginProvider login = new LoginProvider(request.Account, request.Password, request.Scopes, LoginType.LOGIN_BY_PASSWORD);
         if (!login.Login(request.Client.Type, request.Client.System, request.Client.DeviceId, ip, request.Client.SessionId, request.Client.Version, app.Id))
         {
             response.RetCode = "0500";
             response.RetMsg = login.PromptInfo.CustomMessage;
             return response;
         }
         CodePrivilege[] privileges = null;
         if (request.Grants != null && request.Grants.Count > 0)
         {
             privileges = new CodePrivilege[request.Grants.Count];
             for (int i = 0; i < request.Grants.Count; i++)
             {
                 privileges[i] = new CodePrivilege {
                     Id = request.Grants[i].Id, Type = request.Grants[i].Type
                 };
             }
         }
         GrantTokenPrivilegeProvider grant = new GrantTokenPrivilegeProvider(app.Appid, login.User.UserId, request.Scopes, request.Client.DeviceId);
         if (!grant.Grant(request.GrantAll, privileges))
         {
             response.RetCode = "0500";
             response.RetMsg = "授权失败,请重试";
             return response;
         }
         response.RetCode = "0000";
         response.RetMsg = "ok";
         response.Data = new GrantResponseDTO.Types.Result
         {
             Code = grant.Auth_Code
         };
         return response;
     }));
 }
예제 #6
0
        public ActionResult Authorize(string appid, string scope, string state, string redirect_uri, string user_code, string login_pwd, GrantCodeRight[] grants, int takeAll)
        {
            string     device_id  = Request.Headers["device-id"];
            OAuthApp   app        = OAuthAppCache.Instance.Find(it => it.APP_CODE.Equals(appid));
            GrantScope scopeModel = ScopeCache.Instance.Find(it => it.SCOPE_CODE.Equals(scope));

            if (app == null)
            {
                return(View("fatal", FuncResult.FailResult("未注册的应用")));
            }
            if (scopeModel == null)
            {
                return(View("fatal", FuncResult.FailResult("无效的授权范围")));
            }
            if (!this.OAuthContext.IsLogined)
            {
                if (string.IsNullOrEmpty(user_code))
                {
                    return(View("fatal", FuncResult.FailResult("必须输入账号")));
                }
                if (string.IsNullOrEmpty(login_pwd))
                {
                    return(View("fatal", FuncResult.FailResult("必须输入密码")));
                }
                string message;
                if (!this.UserLogin(user_code, login_pwd, app.APP_ID, out message))
                {
                    return(View("fatal", FuncResult.FailResult(message)));
                }
            }
            user_code = this.OAuthContext.UserInfo.UserCode;
            GrantProvider grant = new GrantProvider(appid, user_code, scope, device_id ?? this.OAuthContext.Device_Id);

            if (!grant.Grant(takeAll == 1, grants))
            {
                return(View("fatal", FuncResult.FailResult("授权失败,请重试")));
            }
            string return_url = xUtils.CombinaRedirectUri(redirect_uri, state, grant.Auth_Code);

            return(Redirect(return_url));
        }
예제 #7
0
        [HttpPost] // api/authorize
        public ResponseResult <GrantResponseDTO> GrantByAccount(GrantByAccountRequestDTO data)
        {
            OAuthApp     app   = OAuthAppCache.Get(data.Appid);
            List <Scope> scope = ScopeCache.Get(data.Scopes.Split(','));

            if (app == null)
            {
                return(Fail <GrantResponseDTO>("无效的应用id", "0400"));
            }
            string        ip    = Request.Headers["X-FORWARD-IP"];
            LoginProvider login = new LoginProvider(data.Account, data.Password, data.Scopes, LoginType.LOGIN_BY_PASSWORD);

            if (!login.Login(data.Client.Type, data.Client.System, data.Client.DeviceId, ip, data.Client.SessionId, data.Client.Version, app.Id))
            {
                return(Fail <GrantResponseDTO>(login.PromptInfo.CustomMessage, "0500"));
            }
            CodePrivilege[] privileges = null;
            if (data.Privileges != null && data.Privileges.Count > 0)
            {
                privileges = new CodePrivilege[data.Privileges.Count];
                for (int i = 0; i < data.Privileges.Count; i++)
                {
                    privileges[i] = new CodePrivilege {
                        Id = data.Privileges[i].Id, Type = data.Privileges[i].Type
                    };
                }
            }
            GrantTokenPrivilegeProvider grant = new GrantTokenPrivilegeProvider(app.Appid, login.User.UserId, data.Scopes, data.Client.DeviceId);

            if (!grant.Grant(data.GrantAll, privileges))
            {
                return(Fail <GrantResponseDTO>("授权失败,请重试", "0500"));
            }
            var response = new GrantResponseDTO
            {
                Code = grant.Auth_Code
            };

            return(Success(response));
        }
예제 #8
0
        [HttpPost("client")] // api/authorize/client
        public ResponseResult <GrantResponseDTO> GrantByToken(GrantByTokenRequestDTO data)
        {
            GrantResponseDTO response = new GrantResponseDTO();
            UserToken        token    = UserToken.FromCipherToken(data.Token);

            if (token == null)
            {
                return(Fail <GrantResponseDTO>("无效的token", "0400"));
            }
            OAuthApp app = OAuthAppCache.Get(data.Appid);

            if (app == null)
            {
                return(Fail <GrantResponseDTO>("无效的应用id", "0400"));
            }
            if (app.Id != token.AppId)
            {
                return(Fail <GrantResponseDTO>("无效的token", "0500"));
            }
            CodePrivilege[] privileges = null;
            if (data.Privileges != null && data.Privileges.Count > 0)
            {
                privileges = new CodePrivilege[data.Privileges.Count];
                for (int i = 0; i < data.Privileges.Count; i++)
                {
                    privileges[i] = new CodePrivilege {
                        Id = data.Privileges[i].Id, Type = data.Privileges[i].Type
                    };
                }
            }
            GrantTokenPrivilegeProvider grant = new GrantTokenPrivilegeProvider(app.Appid, token.UserId, data.Scopes, data.Client.DeviceId);

            if (!grant.Grant(data.GrantAll, privileges))
            {
                return(Fail <GrantResponseDTO>("授权失败,请重试"));
            }
            response.Code = grant.Auth_Code;
            return(Success(response));
        }
예제 #9
0
        public ActionResult Authorize(string appid, string scope, string state, string redirect_uri)
        {
            string authHeader = Request.Headers["auth"];
            string device_id  = Request.Headers["device-id"];
            string appVersion = Request.Headers["app-version"];

            Log.Info("HTTP HEADER: auth={0}&device_id={1}&app-version={2}", authHeader, device_id, appVersion);
            if (!string.IsNullOrEmpty(authHeader))
            {
                scope = string.IsNullOrEmpty(scope) ? "basic_api" : scope;
                string message;
                try
                {
                    if (!this.LoginByToken(authHeader, device_id, appVersion, out message))
                    {
                        return(View("fatal", message));
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    Log.Info("APP登录失败", ex);
                    return(View("fatal", new { Message = message }));
                }
            }

            OAuthApp app = OAuthAppCache.Instance.Find(it => it.APP_CODE.Equals(appid));

            //var scopeModel = ScopeCache.Instance.Find(it => it.SCOPE_CODE.Equals(scope));
            GrantScope[] scopeModel = ScopeCache.Instance.FindAll(scope);
            if (scopeModel == null || scopeModel.Length <= 0)
            {
                return(View("fatal", FuncResult.FailResult("无效的授权范围")));
            }
            var scopeids    = scopeModel.Select(it => it.SCOPE_ID);
            var scopeRights = ScopeRightProvider.GetScopeRights(scopeids.ToArray());

            ViewBag.ScopeRights = scopeRights;
            if (app == null)
            {
                return(View("fatal", FuncResult.FailResult("未注册的应用")));
            }
            this.OAuthContext.CurrentApp = app;

            if (string.IsNullOrEmpty(redirect_uri))
            {
                return(View("fatal", FuncResult.FailResult("redirect_uri不能为空")));
            }
            if (this.OAuthContext.IsLogined)                                                                                //已登录
            {
                bool isAlreadyAuthorized = xUtils.IsAlreayAuthorized(app.APP_ID, this.OAuthContext.UserInfo.UserId, scope); //是否已授权

                if (app.IS_INTERNAL || !scopeModel.HasExpllicit() || isAlreadyAuthorized)                                   //内部应用、隐式授权作用域以及已经授权过
                {
                    GrantProvider provider = new GrantProvider(appid, this.OAuthContext.UserInfo.UserCode, scope, device_id ?? this.OAuthContext.Device_Id);
                    if (!provider.Grant(!isAlreadyAuthorized, null))//获取授权作用范围内所有权限
                    {
                        return(View("fatal", FuncResult.FailResult("授权失败")));
                    }
                    string auth_code  = provider.Auth_Code;
                    string return_url = xUtils.CombinaRedirectUri(redirect_uri, state, auth_code);
                    return(Redirect(return_url));
                }
                else
                {
                    //显式授权
                    return(View());
                }
            }
            else//未登录
            {
                if (app.IS_INTERNAL)
                {
                    return(View("Internal_Login"));
                }
                //登录后授权
                return(View());
            }
        }
예제 #10
0
 /// <summary>
 /// 生成用户授权访问令牌
 /// </summary>
 /// <returns></returns>
 public bool GenerateUserToken()
 {
     try
     {
         if (_app == null && !_appid.HasValue)
         {
             Alert(Winner.Framework.Utils.ResultType.无效数据类型, "无效的应用编号");
             return(false);
         }
         if (_app == null)
         {
             _app = OAuthAppCache.Get(_appid.Value);
         }
         this.OAuthUser.Expire_In         = _app.TokenExpireIn;
         this.OAuthUser.Refresh_Expire_In = 30;
         var   fac  = UserModuleFactory.GetUserModuleInstance();
         IUser user = fac?.GetUserByID(_userid);
         if (user == null)
         {
             Alert(Winner.Framework.Utils.ResultType.数据库查不到数据, "用户不存在");
             return(false);
         }
         if (_daCode == null)
         {
             //_daCode = new Tauth_Code();
             _daCode = DaoFactory.Tauth_Code();
             if (this._authid.HasValue)
             {
                 if (!_daCode.SelectByPk(this._authid.Value))
                 {
                     Alert(Winner.Framework.Utils.ResultType.无效数据类型, "无效的授权码");
                     return(false);
                 }
             }
             else
             {
                 _daCode.App_Id      = _app.Id;
                 _daCode.Expire_Time = DateTime.Now.AddMinutes(5);
                 _daCode.Grant_Code  = Guid.NewGuid().ToString("N").ToLower();
                 _daCode.Scope_Id    = ScopeCache.Get(this._scope).Id;
                 _daCode.User_Id     = user.UserId;
                 _daCode.Device_Id   = _deviceid;
                 _daCode.Remarks     = "客户端登录自动授权";
                 _daCode.Status      = 1;
                 if (!_daCode.Insert())
                 {
                     Alert(Winner.Framework.Utils.ResultType.非法操作, "登录授权失败");
                     return(false);
                 }
             }
         }
         int    refresh_token_expire_in = this.OAuthUser.Refresh_Expire_In * 86400;
         string userCode = user.GetUserVoucher(UserVoucherType.自定义号码);
         string open_id  = EncryptOpenId(_app.Id, user.UserId, userCode, _app.UidEncryptKey);
         this.OAuthUser.Open_Id       = open_id;
         this.OAuthUser.Token         = EncryptAccessToken(user.UserId, userCode, _app.Id, this.OAuthUser.Expire_In);
         this.OAuthUser.Refresh_Token = EncryptAccessToken(user.UserId, userCode, _app.Id, refresh_token_expire_in);
         BeginTransaction();
         //Tauth_Token daToken = new Tauth_Token();
         var daToken = DaoFactory.Tauth_Token();
         daToken.ReferenceTransactionFrom(Transaction);
         bool exist = daToken.SelectByAppId_UserId_DeviceId(_app.Id, this._userid, this._deviceid);
         daToken.App_Id          = _app.Id;
         daToken.Expire_Time     = DateTime.Now.AddSeconds(this.OAuthUser.Expire_In);
         daToken.Refresh_Timeout = DateTime.Now.AddDays(this.OAuthUser.Refresh_Expire_In);
         daToken.Refresh_Token   = this.OAuthUser.Refresh_Token;
         daToken.Token_Code      = this.OAuthUser.Token;
         daToken.Scope_Id        = _daCode.Scope_Id;
         daToken.User_Id         = _userid;
         daToken.Grant_Id        = _daCode.Auth_Id;
         daToken.Device_Id       = this._deviceid;
         if (exist)
         {
             daToken.Last_Access_Time = DateTime.Now;
             if (!daToken.Update())
             {
                 Rollback();
                 Alert(Winner.Framework.Utils.ResultType.数据库更新失败, "TOKEN生成失败");
                 return(false);
             }
         }
         else
         {
             if (!daToken.Insert())
             {
                 Rollback();
                 Alert(Winner.Framework.Utils.ResultType.数据库更新失败, "TOKEN生成失败");
                 return(false);
             }
         }
         this.TokenId = daToken.Token_Id;
         Commit();
         return(true);
     }
     catch (Exception ex)
     {
         Log.Error("生成token失败", ex);
         Alert(ResultType.系统异常, "生成token失败");
         return(false);
     }
 }
예제 #11
0
 /// <summary>
 /// 用户授权访问令牌管理功能
 /// </summary>
 /// <param name="app"></param>
 /// <param name="userid"></param>
 /// <param name="dao"></param>
 /// <param name="deviceid"></param>
 public UserTokenProvider(OAuthApp app, int userid, ITauth_Code dao, string scope) : this(app?.Id, userid, dao?.Auth_Id, dao.Device_Id, scope)
 {
     this._daCode = dao;
     this._app    = app;
 }
예제 #12
0
        public AuthenticationProperties GetAppProperties(string authorizationTrackId, OAuthApp app, Usuario participante)
        {
            IDictionary <string, string> data = new Dictionary <string, string>
            {
                { MarketplaceClaimTypes.AuthorizationId, authorizationTrackId },
                { MarketplaceClaimTypes.Name, EscapeDataString(string.IsNullOrEmpty(participante.Nome) ? "" : participante.Nome) },
                //{MarketplaceClaimTypes.CatalogId, participante.Nivel.ToString() },
                { MarketplaceClaimTypes.ProfileId, participante.Id.ToString() },
                { MarketplaceClaimTypes.Scopes, String.Join(",", app.Scopes) },
                { MarketplaceClaimTypes.CampaignId, campaignId }
            };

            return(new AuthenticationProperties(data));
        }
예제 #13
0
        /// <summary>
        /// 执行授权
        /// </summary>
        /// <returns></returns>
        public bool Grant(bool takeAll, params CodePrivilege[] rights)
        {
            OAuthApp app = OAuthAppCache.Get(this._appid);

            if (app == null)
            {
                Alert("未注册的应用");
                return(false);
            }
            string[] scopeCodes = this._scope.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var      scope      = ScopeCache.Get(scopeCodes);

            if (scope == null || scope.Count <= 0)
            {
                Alert("未定义的授权类型");
                return(false);
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByID(this._userId);

            if (user == null)
            {
                Alert("用户信息加载失败");
                return(false);
            }
            if (CheckAlreadyAuth(app.Id, user.UserId))
            {
                return(true);
            }
            if (takeAll && (rights == null || rights.Length <= 0))
            {
                var temp = ScopeRightProvider.GetScopeRights(this._scope);
                rights = new CodePrivilege[temp.Count];
                for (int i = 0; i < rights.Length; i++)
                {
                    rights[i] = new CodePrivilege
                    {
                        Id   = temp[i].Right_Id,
                        Type = temp[i].Right_Type
                    };
                }
            }
            this.Auth_Code = Guid.NewGuid().ToString("N");
            //Tauth_Code daCode = new Tauth_Code();
            var daCode = DaoFactory.Tauth_Code();

            daCode.App_Id      = app.Id;
            daCode.Expire_Time = DateTime.Now.AddMinutes(5);
            daCode.Grant_Code  = this.Auth_Code;
            daCode.Scope_Id    = scope.FirstOrDefault().Id;
            daCode.User_Id     = user.UserId;
            daCode.Device_Id   = this._device_id;
            if (rights != null && rights.Length > 0)
            {
                daCode.Right_Json = Javirs.Common.Json.JsonSerializer.JsonSerialize(rights);
            }
            if (!daCode.Insert())
            {
                Alert("授权失败,请重试!");
                return(false);
            }
            return(true);
        }