private void HandleUnauthorizedRequest( AuthorizationContext filterContext, AuthorizeResult authorizeResult )
 {
   filterContext.Result = new HttpStatusCodeResult( authorizeResult.StatusCodeAsInt );
 }
        /// <summary>
        /// Stop processing the action and return HttpUnauthorizedResult
        /// </summary>
        /// <param name="filterContext">The filter context</param>
        /// <param name="authorizeResult">The authorize result</param>
        protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext, AuthorizeResult authorizeResult)
        {
            // let the application handle itself
            //if (authorizeResult == AuthorizeResult.FailedNotLoggedIn)
            //{
            //    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
            //    return;
            //}

            // handle the unauthorized request
            if (ActiveRoleEngine.ProcessUnauthorizedRequest != null)
            {
                ActiveRoleEngine.ProcessUnauthorizedRequest(filterContext, authorizeResult);
            }
            else
            {
                // if the ProcessUnauthorizedRequest is not defined, return 403 forbidden code
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context</param>
        /// <exception cref="T:System.ArgumentNullException">filterContext</exception>
        /// <exception cref="T:System.InvalidOperationException">ActivePermissionAttribute: Cannot Use Within Child Action Cache</exception>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //filterContext.Controller.ControllerContext.

            if (filterContext == null)
            {
                throw new ArgumentNullException(nameof(filterContext));
            }

            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                // If a child action cache block is active, we need to fail immediately, even if authorization
                // would have succeeded. The reason is that there's no way to hook a callback to rerun
                // authorization before the fragment is served from the cache, so we can't guarantee that this
                // filter will be re-run on subsequent requests.

                // MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache
                throw new InvalidOperationException("ActivePermissionAttribute: Cannot Use Within Child Action Cache");
            }

            #region Skip Authorization

            /*
             * Skip the authorization if
             * - Controller / Action has AllowAnonymousAttribute
             * - Action is NonAction
             * - Action is child action
             *
             * */

            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) ||
                filterContext.ActionDescriptor.IsDefined(typeof(NonActionAttribute), inherit: true) ||
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true))
            {
                return;
            }

            // Authorization must be done at Root action
            if (filterContext.IsChildAction)
            {
                return;
            }

            #endregion Skip Authorization

            AuthorizeResult authorizeResult = AuthorizeUser(filterContext);

            if (authorizeResult == AuthorizeResult.Success)
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));

                // add the authorization handler for cache
                // data is filterContext
                cachePolicy.AddValidationCallback(CacheAuthorizationHandler, filterContext);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext, authorizeResult);

                // Always set the filterContext.Result to stop processing the action
                if (filterContext.Result == null)
                {
                    filterContext.Result = new EmptyResult();
                }
            }
        }
Exemplo n.º 4
0
        public CafeAuthResult EndLogin(IAsyncResult asyncResult)
        {
            LoginResponse loginResponse = this.connection.EndLogin(asyncResult);

            if (loginResponse == null)
            {
                Log <CafeAuthService> .Logger.Warn("Failed to connect to Session server while processing AsyncResult.");

                return(null);
            }
            Log <CafeAuthService> .Logger.InfoFormat("Initial response received from Session server: [{0}]", loginResponse);

            if (loginResponse.Option == Option.NoOption && (loginResponse.Result == AuthorizeResult.Allowed || loginResponse.Result == AuthorizeResult.Terminate))
            {
                Log <CafeAuthService> .Logger.ErrorFormat("Unexpected response from Session server: [{0}]", loginResponse);
            }
            AuthorizeResult result            = loginResponse.Result;
            Option          option            = loginResponse.Option;
            bool            reloginRequired   = false;
            bool            isShutDownEnabled = false;
            int             pcroomNo          = 0;

            if (loginResponse.ExtendInfos != null)
            {
                if (loginResponse.ExtendInfos.IsShutDownEnabled)
                {
                    result = AuthorizeResult.Terminate;
                    option = Option.AccountShutdowned;
                }
                if (loginResponse.ExtendInfos.IsNeedShutDown)
                {
                    if (loginResponse.ExtendInfos.ShutDownErrorCode == PolicyInfoErrorCode.CannotAutholizing || loginResponse.ExtendInfos.ShutDownErrorCode == PolicyInfoErrorCode.CannotFindAgeInfo)
                    {
                        reloginRequired = true;
                    }
                    else if (loginResponse.ExtendInfos.ShutDownErrorCode != PolicyInfoErrorCode.Success)
                    {
                        isShutDownEnabled = true;
                    }
                }
                else if (loginResponse.ExtendInfos.ShutDownTime != DateTime.MinValue)
                {
                    double totalMinutes = (loginResponse.ExtendInfos.ShutDownTime - DateTime.Now).TotalMinutes;
                    int    num;
                    if (totalMinutes <= 30.0)
                    {
                        num = 0;
                    }
                    else
                    {
                        num = (int)(totalMinutes - 30.0);
                    }
                    if (!this.ScheduleShutdownMessageNexonID.Contains(loginResponse.NexonID))
                    {
                        this.ScheduleShutdownMessageNexonID.Add(loginResponse.NexonID);
                        Scheduler.Schedule(base.Thread, Job.Create <Option, ExtendInformation, int, string>(new Action <Option, ExtendInformation, int, string>(this.NotifyMessage), Option.NoOption, loginResponse.ExtendInfos, 0, loginResponse.NexonID), num * 60 * 1000);
                    }
                    Scheduler.Schedule(base.Thread, Job.Create <string>(new Action <string>(this.Kick_User), loginResponse.NexonID), (int)totalMinutes * 60 * 1000 + 300000);
                }
                if (loginResponse.ExtendInfos.PCRoomNo > 0)
                {
                    pcroomNo = loginResponse.ExtendInfos.PCRoomNo;
                }
            }
            return(new CafeAuthResult
            {
                Result = result,
                Option = option,
                SessionNo = loginResponse.SessionNo,
                IsShutDownEnabled = isShutDownEnabled,
                CafeLevel = 1,
                ReloginRequired = reloginRequired,
                PCRoomNo = pcroomNo
            });
        }
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        public async Task Invoke(HttpContext context)
        {
            // 如果是匿名访问路径,则直接跳过
            if (_anonymousPathList.Contains(context.Request.Path.Value))
            {
                await _next(context);

                return;
            }
            var result = context.Request.Headers.TryGetValue("Authorization", out var authStr);

            if (!result || string.IsNullOrWhiteSpace(authStr.ToString()))
            {
                throw new UnauthorizedAccessException("未授权,请传递Header头的Authorization参数");
            }
            // 校验以及自定义校验
            var codeResult = _tokenValidator.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), _options,
                                                      _validatePayload);

            if (codeResult == Code.Ok)
            {
                await _next(context);
            }
            else
            {
                var content = new AuthorizeResult(codeResult, codeResult.Description());
                switch (codeResult)
                {
                case Code.Ok:
                    break;

                case Code.Unauthorized:
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.TokenInvalid:
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Forbidden:
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.NoFound:
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.MethodNotAllowed:
                    context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.HttpRequestError:
                    context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Locked:
                    context.Response.StatusCode = (int)HttpStatusCode.Locked;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Error:
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                default:
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync(content.ToJson());

                    break;
                }
                return;
            }


            //if (!result)
            //{
            //    //var content = new AuthorizeResult(codeResult, codeResult.Description());
            //    //await context.Response.WriteAsync(content.ToJson());
            //    ////context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            //    //return;

            //    throw new UnauthorizedAccessException("验证失败,请查看传递的参数是否正确或是否有权限访问该地址。");
            //}

            //await _next(context);
        }
Exemplo n.º 6
0
        public Message GetLogin(string email, string password, string clientId)
        {
            try
            {
                WebOperationContext current = WebOperationContext.Current;
                if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(clientId))
                {
                    return(ExtHttp.GetJsonStream(new AuthorizeResult {
                        Error = "Denied! Inputs wrong "
                    }, current));
                }

                using (GamePortalEntities gamePortal = new GamePortalEntities())
                {
                    AuthorizeResult result  = new AuthorizeResult();
                    ApiUser         apiUser = gamePortal.ApiUsers.FirstOrDefault(p => p.email == email);
                    User            gpUser;

                    //регистрируем пользоваеля
                    if (apiUser == null)
                    {
                        gpUser = new User()
                        {
                            Login = Guid.NewGuid().ToString()
                        };
                        gamePortal.Users.Add(gpUser);

                        apiUser = new ApiUser()
                        {
                            uid = gpUser.Login, first_name = email.Split('@')[0], last_name = "", photo = "", ClientId = clientId
                        };
                        gpUser.ApiUsers.Add(apiUser);
                    }
                    else
                    {
                        gpUser = apiUser.User;
                    }


                    //Если пароль устанавливается впервые
                    if (string.IsNullOrWhiteSpace(gpUser.Password))
                    {
                        if (!string.IsNullOrWhiteSpace(password))
                        {
                            gpUser.Password = password;
                        }
                        else
                        {
                            result.Error += "Error! Password is not set. Set password. ";
                        }
                    }

                    //Если устанавливается новый email
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        if (apiUser.email != email)
                        {
                            if (gpUser.Password == password)
                            {
                                apiUser.emailConfirm = false;
                                apiUser.email        = email;
                            }
                            else
                            {
                                result.Error += "Error set email! Password wrong. ";
                            }
                        }
                    }

                    //Если email не подтвержён
                    if (string.IsNullOrWhiteSpace(apiUser.email))
                    {
                        result.Error += "Error! Email is empty. Set your email. ";
                    }
                    else if (!apiUser.email.Contains('@'))
                    {
                        result.Error += "Error! Email is not correct. Check your email. ";
                    }
                    else if (!apiUser.emailConfirm)
                    {
                        result.Error += "Error! Email is not confirmed. ";

                        DateTimeOffset dateTimeNow = DateTimeOffset.UtcNow;
                        if (apiUser.resetPswDate == null || (dateTimeNow - apiUser.resetPswDate.Value).TotalMinutes > 15)
                        {
                            try
                            {
                                apiUser.resetPswCode = Guid.NewGuid().ToString();
                                apiUser.resetPswDate = dateTimeNow;
                                MyLibrary.EMail.Send(apiUser.email, "AGOT: online", $"<a href='http://lantsev1981.pro:6999/WebHttpService/ChangeEmail/?code={apiUser.resetPswCode}'>Click the link to confirm the email.</a>", null, true);
                                result.Error += $"Attention! Confirmation link was send to address '{apiUser.email.Substring(0, 5)}...'. Click the link in your email. ";
                            }
                            catch
                            {
                                apiUser.resetPswCode = null;
                                apiUser.resetPswDate = dateTimeNow;
                                result.Error        += "Error! Confirmation link not send! Try again in 15 minutes. ";
                            }
                        }
                        else
                        {
                            result.Error += $"Denied! Confirmation link not send! Try again in {15 - (int)(dateTimeNow - apiUser.resetPswDate.Value).TotalMinutes} minutes. ";
                        }
                    }

                    //Если изменился ключ доступа
                    if (apiUser.ClientId != clientId)
                    {
                        if (gpUser.Password == password)
                        {
                            apiUser.ClientId       = clientId;
                            apiUser.LastConnection = DateTimeOffset.UtcNow;
                            gpUser.Version         = Guid.NewGuid();
                        }
                        else
                        {
                            result.Error += "Error update profile! Password wrong. ";
                        }
                    }
                    else
                    {
                        apiUser.LastConnection = DateTimeOffset.UtcNow;
                        gpUser.Version         = Guid.NewGuid();
                    }

                    gamePortal.SaveChanges();

                    if (apiUser.ClientId == clientId)
                    {
                        result.Email = apiUser.email;
                    }

                    if (string.IsNullOrWhiteSpace(result.Error))
                    {
                        result.Login = gpUser.Login;
                    }

                    return(ExtHttp.GetJsonStream(result, current));
                }
            }
            catch (Exception exp)
            {
                GameService.GameException.NewGameException(null, "GetLogin", exp, false);
                return(null);
            }
        }