private static PasswordAuthentication GetSystemCreds(AuthScope authscope, Authenticator.RequestorType
                                                      requestorType)
 {
     return(Authenticator.RequestPasswordAuthentication(authscope.GetHost(), null, authscope
                                                        .GetPort(), "http", null, TranslateScheme(authscope.GetScheme()), null, requestorType
                                                        ));
 }
Ejemplo n.º 2
0
 public void TestTearDown()
 {
     if (AuthScope.HasCurrent)
     {
         AuthScope.Dispose();
     }
 }
        /// <summary>
        /// Find matching
        /// <see cref="Apache.Http.Auth.Credentials">credentials</see>
        /// for the given authentication scope.
        /// </summary>
        /// <param name="map">the credentials hash map</param>
        /// <param name="authscope">
        /// the
        /// <see cref="Apache.Http.Auth.AuthScope">authentication scope</see>
        /// </param>
        /// <returns>the credentials</returns>
        private static Credentials MatchCredentials(IDictionary <AuthScope, Credentials> map
                                                    , AuthScope authscope)
        {
            // see if we get a direct hit
            Credentials creds = map.Get(authscope);

            if (creds == null)
            {
                // Nope.
                // Do a full scan
                int       bestMatchFactor = -1;
                AuthScope bestMatch       = null;
                foreach (AuthScope current in map.Keys)
                {
                    int factor = authscope.Match(current);
                    if (factor > bestMatchFactor)
                    {
                        bestMatchFactor = factor;
                        bestMatch       = current;
                    }
                }
                if (bestMatch != null)
                {
                    creds = map.Get(bestMatch);
                }
            }
            return(creds);
        }
Ejemplo n.º 4
0
        private void DoPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState
                                      , CredentialsProvider credsProvider)
        {
            string schemeName = authScheme.GetSchemeName();

            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
            }
            AuthScope   authScope = new AuthScope(host, AuthScope.AnyRealm, schemeName);
            Credentials creds     = credsProvider.GetCredentials(authScope);

            if (creds != null)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("BASIC", authScheme.GetSchemeName()))
                {
                    authState.SetState(AuthProtocolState.Challenged);
                }
                else
                {
                    authState.SetState(AuthProtocolState.Success);
                }
                authState.Update(authScheme, creds);
            }
            else
            {
                this.log.Debug("No credentials for preemptive authentication");
            }
        }
        public virtual Credentials GetCredentials(AuthScope authscope)
        {
            Args.NotNull(authscope, "Auth scope");
            Credentials localcreds = @internal.GetCredentials(authscope);

            if (localcreds != null)
            {
                return(localcreds);
            }
            if (authscope.GetHost() != null)
            {
                PasswordAuthentication systemcreds = GetSystemCreds(authscope, Authenticator.RequestorType
                                                                    .Server);
                if (systemcreds == null)
                {
                    systemcreds = GetSystemCreds(authscope, Authenticator.RequestorType.Proxy);
                }
                if (systemcreds != null)
                {
                    return(new UsernamePasswordCredentials(systemcreds.GetUserName(), new string(systemcreds
                                                                                                 .GetPassword())));
                }
            }
            return(null);
        }
Ejemplo n.º 6
0
 public static void ATAuthPartial(this HtmlHelper html, AuthScope scope, int minlevel, int maxlevel, string partialName)
 {
     if (CheckAuthorization(scope, minlevel, maxlevel, html.ViewContext.RouteData.Values))
     {
         html.RenderPartial(partialName);
     }
 }
        public void Empty()
        {
            var empty = new AuthScope();

            Assert.True(empty.IsEmpty);
            Assert.True(AuthScope.Empty.IsEmpty);
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> InitData()
        {
            return(await RunActionAsync(async() =>
            {
                var now = DateTime.Now;

                if (!await this._AuthScopeRepository.ExistAsync(null))
                {
                    var model = new AuthScope()
                    {
                        Name = "all",
                        DisplayName = "全部权限",
                        Description = "全部权限",
                        Important = (int)YesOrNoEnum.是,
                        Sort = 0,
                        IsDefault = (int)YesOrNoEnum.是,
                        ImageUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        FontIcon = "fa fa-star"
                    };
                    model.Init();

                    await this._AuthScopeRepository.AddAsync(model);
                }

                var client_id = this._IValidationDataProvider.GetClientID(this.X.context);
                var client_security = this._IValidationDataProvider.GetClientSecurity(this.X.context);

                if (!ValidateHelper.IsAllPlumpString(client_id, client_security))
                {
                    return Content("default client data is empty");
                }

                if (!await this._AuthClientRepository.ExistAsync(x => x.UID == client_id && x.ClientSecretUID == client_security))
                {
                    await this._AuthClientRepository.DeleteWhereAsync(x => x.UID == client_id || x.ClientSecretUID == client_security);
                    var official = new AuthClient()
                    {
                        UID = client_id,
                        ClientName = "auth管理端",
                        Description = "auth管理端",
                        ClientUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        LogoUrl = "http://images.qipeilong.cn/ico/logo.png?t=111",
                        UserUID = "http://www.baidu.com/",
                        ClientSecretUID = client_security,
                        IsRemove = (int)YesOrNoEnum.否,
                        IsActive = (int)YesOrNoEnum.是,
                        CreateTime = now,
                        UpdateTime = now
                    };

                    await this._AuthClientRepository.AddAsync(official);
                }

                return Content("ok");
            }));
        }
        public void Single()
        {
            const string Expected = "email";

            var scope = new AuthScope(Expected);

            Assert.Equal(1, scope.Count);
            Assert.Equal(Expected, scope);
            Assert.True(Expected == scope);
            Assert.False(Expected != scope);
            Assert.Equal(Expected, scope.StringValue);
        }
Ejemplo n.º 10
0
 public async Task <IActionResult> SaveScope(AuthScope scope)
 {
     if (scope.Id == null)
     {
         scope.Id = Guid.NewGuid();
         SqlHelper.Insert <AuthScope>(scope, connectionString);
     }
     else
     {
         SqlHelper.Update <AuthScope>(scope, connectionString);
     }
     return(Ok());
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="authScopeId">The rest user identifier.</param>
        public void ShowDetail(int authScopeId)
        {
            var rockContext = new RockContext();

            AuthScope authScope = null;
            var       isNew     = authScopeId.Equals(0);

            if (!isNew)
            {
                authScope   = new AuthScopeService(rockContext).Get(authScopeId);
                lTitle.Text = ActionTitle.Edit("Scope").FormatAsHtmlTitle();
            }
            else
            {
                lTitle.Text = ActionTitle.Add("Scope").FormatAsHtmlTitle();
            }

            if (authScope == null)
            {
                if (!isNew)
                {
                    DisplayErrorMessage("The Auth Scope with the specified Id was found.");
                    return;
                }

                authScope = new AuthScope {
                    Id = 0, IsActive = true
                };
            }

            hfRestUserId.Value = authScope.Id.ToString();

            tbName.Text       = authScope.Name;
            tbPublicName.Text = authScope.PublicName;
            cbActive.Checked  = authScope.IsActive;

            nbEditModeMessage.Text = string.Empty;
            if (authScope.IsSystem)
            {
                tbName.Enabled         = false;
                cbActive.Enabled       = false;
                nbEditModeMessage.Text = EditModeMessage.System(Rock.Model.AuthScope.FriendlyTypeName);
            }

            var editAllowed = authScope.IsAuthorized(Authorization.EDIT, CurrentPerson);

            lbSave.Visible = editAllowed;
        }
        public void Multiple()
        {
            const string Expected = "openid email profile";

            AuthScope scope = Expected;

            Assert.Equal(3, scope.Count);
            Assert.Contains("openid", scope.Items);
            Assert.Contains("email", scope.Items);
            Assert.Contains("profile", scope.Items);

            var differentOrder = (AuthScope)"email openid profile";

            Assert.Equal(scope, differentOrder);
            Assert.True(scope == differentOrder);
            Assert.False(differentOrder != scope);
        }
Ejemplo n.º 13
0
            /// <exception cref="Apache.Http.HttpException"></exception>
            /// <exception cref="System.IO.IOException"></exception>
            public void Process(HttpWebRequest request, HttpContext context)
            {
                AuthState authState = (AuthState)context.GetAttribute(ClientContext.TargetAuthState
                                                                      );
                CredentialsProvider credsProvider = (CredentialsProvider)context.GetAttribute(ClientContext
                                                                                              .CredsProvider);
                HttpHost targetHost = (HttpHost)context.GetAttribute(ExecutionContext.HttpTargetHost
                                                                     );

                if (authState.GetAuthScheme() == null)
                {
                    AuthScope authScope = new AuthScope(targetHost.GetHostName(), targetHost.GetPort(
                                                            ));
                    authState.SetAuthScheme(new BasicScheme());
                    authState.SetCredentials(creds);
                }
            }
Ejemplo n.º 14
0
 public static bool CheckAuthorization(HttpContext httpContext, Site site, CourseTerm courseTerm, AuthScope scope, int minLevel, int maxLevel)
 {
     AssessTrackDataRepository data = new AssessTrackDataRepository();
     if (httpContext == null)
     {
         throw new ArgumentNullException("httpContext");
     }
     IPrincipal user = httpContext.User;
     if (!user.Identity.IsAuthenticated)
     {
         return false;
     }
     //Get the user's profile and see if they have
     //the required access level
     Profile profile = data.GetLoggedInProfile();
     switch (scope)
     {
         case AuthScope.Application:
             {
                 if (profile.AccessLevel < minLevel || profile.AccessLevel > maxLevel)
                     return false;
                 break;
             }
         case AuthScope.Site:
             {
                 SiteMember member = data.GetSiteMemberByMembershipID(site,profile.MembershipID);
                 if (member == null ||
                     (member.AccessLevel < minLevel || member.AccessLevel > maxLevel))
                     return false;
             }
             break;
         case AuthScope.CourseTerm:
             {
                 CourseTermMember member = data.GetCourseTermMemberByMembershipID(courseTerm, profile.MembershipID);
                 if (member == null ||
                     (member.AccessLevel < minLevel || member.AccessLevel > maxLevel))
                     return false;
             }
             break;
         default:
             //TODO Do some logging here maybe?
             return false;
     }
     return true;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Saves the authentication scope.
        /// </summary>
        /// <param name="authScopeId">The authentication scope identifier.</param>
        private void SaveAuthScope(int authScopeId)
        {
            var isNew = authScopeId.Equals(0);

            var authScope = new AuthScope();

            var editAllowed = authScope.IsAuthorized(Authorization.EDIT, CurrentPerson);

            if (!editAllowed)
            {
                DisplayErrorMessage("The current user is not authorized to make changes.");
                return;
            }

            var rockContext      = new RockContext();
            var authScopeService = new AuthScopeService(rockContext);

            if (isNew)
            {
                authScopeService.Add(authScope);
            }
            else
            {
                authScope = authScopeService.Get(authScopeId);
            }

            if (authScope == null)
            {
                DisplayErrorMessage("The Auth Scope with the specified Id was found.");
                return;
            }

            if (!authScope.IsSystem)
            {
                authScope.Name     = tbName.Text;
                authScope.IsActive = cbActive.Checked;
            }

            authScope.PublicName = tbPublicName.Text;

            rockContext.SaveChanges();
        }
Ejemplo n.º 16
0
 public async Task <ActionResult> SaveScopeAction(AuthScope model)
 {
     return(await RunActionAsync(async() =>
     {
         if (model == null)
         {
             return GetJsonRes("参数错误");
         }
         if (ValidateHelper.IsPlumpString(model.UID))
         {
             var res = await this._IAuthScopeService.UpdateScopeAsync(model);
             return GetJsonRes(res);
         }
         else
         {
             var res = await this._IAuthScopeService.AddScopeAsync(model);
             return GetJsonRes(res);
         }
     }));
 }
Ejemplo n.º 17
0
        public static string ATAuthLink(this HtmlHelper html, string linkText, string before, string after, object routeValues, AuthScope scope, int minLevel, int maxLevel)
        {
            RouteValueDictionary routeValuesDict = new RouteValueDictionary(html.ViewContext.RouteData.Values);
            //routeValuesDict

            foreach (PropertyInfo prop in routeValues.GetType().GetProperties())
            {
                string name = prop.Name;
                string val = prop.GetValue(routeValues, null).ToString();
                routeValuesDict[name] = val;
                //html.ViewContext.RouteData.Values.Add(name,val);
            }
            if (CheckAuthorization(scope, minLevel, maxLevel, routeValuesDict))
            {
                RouteValueDictionary newValues = new RouteValueDictionary(routeValues);
                if (newValues["controller"] == null)
                {
                    newValues["controller"] = routeValuesDict["controller"];
                }
                return before + HtmlHelper.GenerateRouteLink(html.ViewContext.RequestContext, html.RouteCollection, linkText, null, newValues, null) + after;
            }
            return "";
        }
 public virtual void SetCredentials(AuthScope authscope, Credentials credentials)
 {
     Args.NotNull(authscope, "Authentication scope");
     credMap.Put(authscope, credentials);
 }
 public virtual Credentials GetCredentials(AuthScope authscope)
 {
     Args.NotNull(authscope, "Authentication scope");
     return(MatchCredentials(this.credMap, authscope));
 }
 public void Unsupported()
 {
     Assert.False(AuthScope.IsScopeSupported("nope", out var unsupported));
     Assert.Equal("nope", unsupported);
 }
Ejemplo n.º 21
0
			/// <exception cref="Apache.Http.HttpException"></exception>
			/// <exception cref="System.IO.IOException"></exception>
			public void Process(HttpWebRequest request, HttpContext context)
			{
				AuthState authState = (AuthState)context.GetAttribute(ClientContext.TargetAuthState
					);
				CredentialsProvider credsProvider = (CredentialsProvider)context.GetAttribute(ClientContext
					.CredsProvider);
				HttpHost targetHost = (HttpHost)context.GetAttribute(ExecutionContext.HttpTargetHost
					);
				if (authState.GetAuthScheme() == null)
				{
					AuthScope authScope = new AuthScope(targetHost.GetHostName(), targetHost.GetPort(
						));
					authState.SetAuthScheme(new BasicScheme());
					authState.SetCredentials(creds);
				}
			}
        /// <exception cref="Apache.Http.Auth.MalformedChallengeException"></exception>
        public virtual Queue <AuthOption> Select(IDictionary <string, Header> challenges, HttpHost
                                                 authhost, HttpResponse response, HttpContext context)
        {
            Args.NotNull(challenges, "Map of auth challenges");
            Args.NotNull(authhost, "Host");
            Args.NotNull(response, "HTTP response");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            Queue <AuthOption>          options  = new List <AuthOption>();
            Lookup <AuthSchemeProvider> registry = clientContext.GetAuthSchemeRegistry();

            if (registry == null)
            {
                this.log.Debug("Auth scheme registry not set in the context");
                return(options);
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return(options);
            }
            RequestConfig        config    = clientContext.GetRequestConfig();
            ICollection <string> authPrefs = GetPreferredAuthSchemes(config);

            if (authPrefs == null)
            {
                authPrefs = DefaultSchemePriority;
            }
            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Authentication schemes in the order of preference: " + authPrefs);
            }
            foreach (string id in authPrefs)
            {
                Header challenge = challenges.Get(id.ToLower(CultureInfo.InvariantCulture));
                if (challenge != null)
                {
                    AuthSchemeProvider authSchemeProvider = registry.Lookup(id);
                    if (authSchemeProvider == null)
                    {
                        if (this.log.IsWarnEnabled())
                        {
                            this.log.Warn("Authentication scheme " + id + " not supported");
                        }
                        // Try again
                        continue;
                    }
                    AuthScheme authScheme = authSchemeProvider.Create(context);
                    authScheme.ProcessChallenge(challenge);
                    AuthScope authScope = new AuthScope(authhost.GetHostName(), authhost.GetPort(), authScheme
                                                        .GetRealm(), authScheme.GetSchemeName());
                    Credentials credentials = credsProvider.GetCredentials(authScope);
                    if (credentials != null)
                    {
                        options.AddItem(new AuthOption(authScheme, credentials));
                    }
                }
                else
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Challenge for " + id + " authentication scheme not available");
                    }
                }
            }
            // Try again
            return(options);
        }
Ejemplo n.º 23
0
        //Will return false if routeData points to non-existant site or courseterm
        public static bool CheckAuthorization(AuthScope scope, int minLevel, int maxLevel, RouteValueDictionary routeData)
        {
            //RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
            AssessTrackDataRepository data = new AssessTrackDataRepository();
            string siteShortName;
            Site site = null;
            string courseTermShortName;
            CourseTerm courseTerm = null;
            //HttpContext.Current.

            if (scope != AuthScope.Application)
            {
                //Try to get the site by shortName
                if (routeData["siteShortName"] != null)
                {
                    siteShortName = routeData["siteShortName"].ToString();
                    site = data.GetSiteByShortName(siteShortName);
                }
                //if scope is Site, then {id} should refer to SiteID
                else if (scope != AuthScope.CourseTerm && routeData["id"] != null)
                {
                    try
                    {

                        Guid siteID = new Guid(routeData["id"].ToString());
                        site = data.GetSiteByID(siteID);
                    }
                    catch
                    {
                        //Do nothing here
                        //if this fails, site will be null and the following code will
                        //return SiteNotFound
                    }
                }

                if (site == null)
                {
                    return false;
                }
                if (scope == AuthScope.CourseTerm)
                {
                    //Try to get the site by shortName
                    if (routeData["courseTermShortName"] != null)
                    {
                        courseTermShortName = routeData["courseTermShortName"].ToString();
                        courseTerm = data.GetCourseTermByShortName(site, courseTermShortName);
                    }
                    //if scope is CourseTerm, then {id} should refer to CourseTermID
                    else if (routeData["id"].ToString() != null)
                    {
                        try
                        {

                            Guid courseTermID = new Guid(routeData["id"].ToString());
                            courseTerm = data.GetCourseTermByID(site, courseTermID);
                        }
                        catch
                        {
                            //Do nothing here
                            //if this fails, courseTerm will be null and the following code will
                            //return CourseTermNotFound
                        }
                    }
                    if (courseTerm == null)
                    {

                        return false;
                    }
                }
            }
            //Set up is complete, now check if the user is authorized
            if (CheckAuthorization(HttpContext.Current, site, courseTerm, scope, minLevel, maxLevel))
            {
                return true;
            }
            else
            {
                return false;

            }
        }
 static AuthConfig getStartConfig(AuthScope scope = null)
 {
     return(AuthConfig
            .Default(RuntimeEnvironment.Migration, "clientId", new Uri("test://redirect"))
            .WithScope(scope));
 }
Ejemplo n.º 25
0
 public static bool CheckAuthorization(this HtmlHelper html, int minlevel, int maxlevel, AuthScope scope)
 {
     return CheckAuthorization(scope, minlevel, maxlevel, html.ViewContext.RouteData.Values);
 }
Ejemplo n.º 26
0
 public static string ATAuthLink(this HtmlHelper html, string linkText, object routeValues, AuthScope scope, int minLevel, int maxLevel)
 {
     return ATAuthLink(html, linkText, string.Empty, string.Empty, routeValues, scope, minLevel, maxLevel);
 }
 public virtual void SetCredentials(AuthScope authscope, Credentials credentials)
 {
     @internal.SetCredentials(authscope, credentials);
 }