Esempio n. 1
0
 /// <summary>
 /// Initializes the default SharePointContextProvider instance.
 /// </summary>
 public static SharePointContextProvider GetInstance(SharePointConfiguration configuration)
 {
     _tokenHandler  = new TokenHandler(configuration);
     _configuration = configuration;
     if (!_tokenHandler.IsHighTrustApp())
     {
         _current = new SharePointAcsContextProvider();
     }
     else
     {
         throw new NotImplementedException("Hight Trust is still not supported by this library.");
         //current = new SharePointHighTrustContextProvider();
     }
     return(_current);
 }
Esempio n. 2
0
        public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj, SharePointConfiguration configuration)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (string.IsNullOrEmpty(contextToken))
            {
                throw new ArgumentNullException(nameof(contextToken));
            }

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

            this.contextToken = contextToken;
            this.contextTokenObj = contextTokenObj;
            this.TokenHandler = new TokenHandler(configuration);
        }
Esempio n. 3
0
        public TokenHandler(SharePointConfiguration configuration)
        {
            _clientId = configuration.ClientId;
            _issuerId = string.IsNullOrEmpty(configuration.IssuerId) ? _clientId : configuration.IssuerId;
            _hostedAppHostNameOverride = configuration.HostedAppHostNameOverride;
            _hostedAppHostName         = configuration.HostedAppHostName;
            _clientSecret          = configuration.ClientSecret;
            _secondaryClientSecret = configuration.SecondaryClientSecret;
            _realm            = configuration.Realm;
            _serviceNamespace = configuration.Realm;

            var clientSigningCertificatePath     = configuration.ClientSigningCertificatePath;
            var clientSigningCertificatePassword = configuration.ClientSigningCertificatePassword;
            var clientCertificate = (string.IsNullOrEmpty(clientSigningCertificatePath) || string.IsNullOrEmpty(clientSigningCertificatePassword)) ? null : new X509Certificate2(clientSigningCertificatePath, clientSigningCertificatePassword);

            _signingCredentials = (clientCertificate == null)
                ? null
                : new X509SigningCredentials(clientCertificate, SecurityAlgorithms.RsaSha256Signature,
                                             SecurityAlgorithms.Sha256Digest);
        }
 /// <summary>
 /// Initializes the default SharePointContextProvider instance.
 /// </summary>
 public static SharePointContextProvider GetInstance(SharePointConfiguration configuration)
 {
     _tokenHandler = new TokenHandler(configuration);
     _configuration = configuration;
     if (!_tokenHandler.IsHighTrustApp())
     {
         _current = new SharePointAcsContextProvider();
     }
     else
     {
         throw new NotImplementedException("Hight Trust is still not supported by this library.");
         //current = new SharePointHighTrustContextProvider();
     }
     return _current;
 }
Esempio n. 5
0
        public TokenHandler(SharePointConfiguration configuration)
        {
            _clientId = configuration.ClientId;
            _issuerId = string.IsNullOrEmpty(configuration.IssuerId) ? _clientId : configuration.IssuerId;
            _hostedAppHostNameOverride = configuration.HostedAppHostNameOverride;
            _hostedAppHostName = configuration.HostedAppHostName;
            _clientSecret = configuration.ClientSecret;
            _secondaryClientSecret = configuration.SecondaryClientSecret;
            _realm = configuration.Realm;
            _serviceNamespace = configuration.Realm;

            var clientSigningCertificatePath = configuration.ClientSigningCertificatePath;
            var clientSigningCertificatePassword = configuration.ClientSigningCertificatePassword;
            var clientCertificate = (string.IsNullOrEmpty(clientSigningCertificatePath) || string.IsNullOrEmpty(clientSigningCertificatePassword)) ? null : new X509Certificate2(clientSigningCertificatePath, clientSigningCertificatePassword);

            _signingCredentials = (clientCertificate == null)
                ? null
                : new X509SigningCredentials(clientCertificate, SecurityAlgorithms.RsaSha256Signature,
                    SecurityAlgorithms.Sha256Digest);
        }
        protected override async Task <AuthenticateResult> HandleRemoteAuthenticateAsync()
        {
            Uri redirectUrl;

            if (string.IsNullOrEmpty(Options.ClientId))
            {
                return(AuthenticateResult.Fail("ClientId is not configured in the appsettings.json file."));
            }

            //Set the default error message when no SP Auth is attempted
            AuthenticateResult result = AuthenticateResult.Fail("Could not handle SharePoint authentication.");

            var authenticationProperties = new AuthenticationProperties()
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(10),
                IsPersistent = false,
                AllowRefresh = false
            };

            // Sets up the SharePoint configuration based on the middleware options.
            var spContextProvider = SharePointContextProvider.GetInstance(
                SharePointConfiguration.GetFromSharePointAuthenticationOptions(Options));

            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
            {
            case RedirectionStatus.Ok:
                _redirectionStatus = RedirectionStatus.Ok;

                // Gets the current SharePoint context
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                // Gets the SharePoint context CacheKey. The CacheKey would be assigned as issuer for new claim.
                // It is also used to validate identity that is authenticated.
                //Currently, we don't support High Trust
                var userCacheKey = ((SharePointAcsContext)spContext).CacheKey;

                // Checks if we already have an authenticated principal
                ClaimsPrincipal principal;
                if (Context.User.Identities.Any(identity =>
                                                identity.IsAuthenticated && identity.HasClaim(x => x.Issuer == GetType().Assembly.GetName().Name)))
                {
                    principal = Context.User;
                }
                else
                {
                    //build a claims identity and principal
                    var identity = new ClaimsIdentity(this.Options.AuthenticationScheme);

                    // Adds claims with the SharePoint context CacheKey as issuer to the Identity object.
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Authentication, userCacheKey, "SPCacheKey", GetType().Assembly.GetName().Name),
                    };

                    identity.AddClaims(claims);

                    principal = new ClaimsPrincipal(identity);

                    // Handles the sign in method of the SP auth middleware
                    await Context.Authentication.SignInAsync
                        (this.Options.AuthenticationScheme, principal, authenticationProperties);

                    //sign in the cookie middleware so it issues a cookie
                    if (!string.IsNullOrWhiteSpace(this.Options.CookieAuthenticationScheme))
                    {
                        SignInAccepted = true;
                        await Context.Authentication.SignInAsync
                            (this.Options.CookieAuthenticationScheme, principal, authenticationProperties);
                    }
                }

                // Creates the authentication ticket.
                var ticket = new AuthenticationTicket(principal, authenticationProperties, this.Options.AuthenticationScheme);
                result = AuthenticateResult.Success(ticket);

                //Throw auth ticket success event
                await Options.SharePointAuthenticationEvents.AuthenticationSucceeded(
                    new Events.AuthenticationSucceededContext(Context, Options)
                {
                    Ticket            = ticket,   //pass the ticket
                    SharePointContext = spContext //append the sp context
                });

                //Log success
                LoggingExtensions.TokenValidationSucceeded(this.Logger);

                break;

            case RedirectionStatus.ShouldRedirect:
                _redirectionStatus = RedirectionStatus.ShouldRedirect;

                Response.StatusCode = 301;
                result = AuthenticateResult.Fail("ShouldRedirect");

                // Signs out so new signin to be performed on redirect back from SharePoint
                await Context.Authentication.SignOutAsync(this.Options.AuthenticationScheme);

                // Redirect to get new context token
                Context.Response.Redirect(redirectUrl.AbsoluteUri);
                break;

            case RedirectionStatus.CanNotRedirect:
                _redirectionStatus = RedirectionStatus.CanNotRedirect;

                result = AuthenticateResult.Fail("No SPHostUrl to build a SharePoint Context, but Authenticate was called on the SharePoint middleware.");

                //Log that we cannot redirect
                LoggingExtensions.CannotRedirect(this.Logger);

                //Throw failed event
                await Options.SharePointAuthenticationEvents.AuthenticationFailed(new Events.AuthenticationFailedContext(Context, Options));

                break;
            }

            return(result);
        }
Esempio n. 7
0
        public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj, SharePointConfiguration configuration)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (string.IsNullOrEmpty(contextToken))
            {
                throw new ArgumentNullException(nameof(contextToken));
            }

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

            this.contextToken    = contextToken;
            this.contextTokenObj = contextTokenObj;
            this.TokenHandler    = new TokenHandler(configuration);
        }
Esempio n. 8
0
 /// <summary>
 /// Initializes the default SharePointContextProvider instance.
 /// </summary>
 public static SharePointContextProvider GetInstance(IOptions <SharePointConfiguration> options)
 {
     //setup the SharePoint configuration based on the middleware options
     return(GetInstance(SharePointConfiguration.GetFromIOptions(options)));
 }
Esempio n. 9
0
        protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync()
        {
            //Set the default error message when no SP Auth is attempted
            HandleRequestResult result = HandleRequestResult.Fail("Could not handle SharePoint authentication.");

            // Sets up the SharePoint configuration based on the middleware options.
            var spContextProvider = SharePointContextProvider.GetInstance(
                SharePointConfiguration.GetFromSharePointAuthenticationOptions(Options));

            switch (SharePointContextProvider.CheckRedirectionStatus(Context, out Uri redirectUrl))
            {
            case RedirectionStatus.Ok:
                // Gets the current SharePoint context
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                // Gets the SharePoint context CacheKey. The CacheKey would be assigned as issuer for new claim.
                // It is also used to validate identity that is authenticated.
                //Currently, we don't support High Trust
                var userCacheKey = ((SharePointAcsContext)spContext).CacheKey;

                // Checks if we already have an authenticated principal
                ClaimsPrincipal principal;
                if (Context.User.Identities.Any(identity =>
                                                identity.IsAuthenticated && identity.HasClaim(x => x.Issuer == ClaimsIssuer)))
                {
                    principal = Context.User;
                }
                else
                {
                    //build a claims identity and principal
                    var identity = new ClaimsIdentity(Scheme.Name);

                    // Adds claims with the SharePoint context CacheKey as issuer to the Identity object.
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Authentication, userCacheKey, "SPCacheKey", ClaimsIssuer)
                    };

                    identity.AddClaims(claims);

                    principal = new ClaimsPrincipal(identity);

                    //Call sign in middleware, defaults to the cookie middleware (if set up) so it issues a cookie, can be overriden
                    await HandleSignInAsync(principal);
                }

                // Creates the authentication ticket.
                var ticket = new AuthenticationTicket(principal, Options.AuthenticationProperties, Options.SignInScheme);
                result = HandleRequestResult.Success(ticket);

                //Throw auth ticket success event
                await Events.AuthenticationSucceeded(
                    new AuthenticationSucceededContext(Context, Scheme, Options, Options.AuthenticationProperties)
                {
                    Ticket            = ticket,   //pass the ticket
                    SharePointContext = spContext //append the sp context
                });

                //Log success
                LoggingExtensions.TokenValidationSucceeded(Logger);

                break;

            case RedirectionStatus.ShouldRedirect:
                Response.StatusCode = 301;
                result = HandleRequestResult.Fail("ShouldRedirect");

                // Signs out so new signin to be performed on redirect back from SharePoint
                await Context.SignOutAsync(Scheme.Name);

                // Redirect to get new context token
                Context.Response.Redirect(redirectUrl.AbsoluteUri);
                break;

            case RedirectionStatus.CanNotRedirect:
                result = HandleRequestResult.Fail("No SPHostUrl to build a SharePoint Context, but Authenticate was called on the SharePoint middleware.");

                //Log that we cannot redirect
                LoggingExtensions.CannotRedirect(Logger);

                //Throw failed event
                await Events.AuthenticationFailed(new AuthenticationFailedContext(Context, Scheme, Options, Options.AuthenticationProperties));

                break;
            }

            return(result);
        }