Esempio n. 1
0
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </summary>
 /// <param name="ctx">Authentication context instance</param>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <returns>It contains Access Token, its expiration time, user information. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public static async Task <AuthenticationResult> AcquireTokenSilentAsync(this AuthenticationContext ctx,
                                                                         string resource,
                                                                         IClientAssertionCertificate clientCertificate, UserIdentifier userId)
 {
     return(await ctx.AcquireTokenSilentCommonAsync(resource,
                                                    new ClientKey(clientCertificate, ctx.Authenticator), userId, null).ConfigureAwait(false));
 }
            public JWTHeaderWithCertificate(IClientAssertionCertificate credential, bool sendX5C)
                : base(credential)
            {
                X509CertificateThumbprint      = this.Credential.Thumbprint;
                X509CertificatePublicCertValue = null;

                if (!sendX5C)
                {
                    return;
                }

                //Check to see if credential is our implementation or developer provided.
                if (credential.GetType().ToString() != "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate")
                {
                    CallState.Default.Logger.Warning(null, "The implementation of IClientAssertionCertificate is developer provided and it should be replaced with library provided implmentation.");
                    return;
                }

#if  NET45
                if (credential is ClientAssertionCertificate cert)
                {
                    X509CertificatePublicCertValue = Convert.ToBase64String(cert.Certificate.GetRawCertData());
                }
#elif NETSTANDARD1_3
                if (credential is ClientAssertionCertificate cert)
                {
                    X509CertificatePublicCertValue = Convert.ToBase64String(cert.Certificate.RawData);
                }
#endif
            }
Esempio n. 3
0
 /// <summary>
 /// Acquires security token from the authority using an authorization code previously received.
 /// This method does not lookup token cache, but stores the result in it, so it can be looked up using other methods such as <see cref="AuthenticationContext.AcquireTokenSilentAsync(string, string, UserIdentifier)"/>.
 /// </summary>
 /// <param name="ctx">Authentication context instance</param>
 /// <param name="authorizationCode">The authorization code received from service authorization endpoint.</param>
 /// <param name="redirectUri">The redirect address used for obtaining authorization code.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token. It can be null if provided earlier to acquire authorizationCode.</param>
 /// <returns>It contains Access Token, its expiration time, user information.</returns>
 public static async Task <AuthenticationResult> AcquireTokenByAuthorizationCodeAsync(
     this AuthenticationContext ctx, string authorizationCode,
     Uri redirectUri, IClientAssertionCertificate clientCertificate, string resource)
 {
     return(await ctx.AcquireTokenByAuthorizationCodeCommonAsync(authorizationCode, redirectUri,
                                                                 new ClientKey(clientCertificate, ctx.Authenticator), resource).ConfigureAwait(false));
 }
Esempio n. 4
0
        static AadAuthentication()
        {
            X509Certificate2 cert = GetCertificateFromStore(ConfigurationManager.AppSettings["Thumbprint"]);

            context     = new AuthenticationContext(ConfigurationManager.AppSettings["AadInstance"] + ConfigurationManager.AppSettings["TenantId"]);
            credentials = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], cert);
        }
            public JWTHeader(IClientAssertionCertificate credential)
            {
                this.Credential = credential;
                _alg            = (this.Credential == null)
                    ? JsonWebTokenConstants.Algorithms.None
                    : JsonWebTokenConstants.Algorithms.RsaSha256;

                _type = JsonWebTokenConstants.HeaderType;
            }
Esempio n. 6
0
        private AzureSecurityCenterForIoTLogAnalyticsClient()
        {
            _client   = new HttpClient();
            _queryUri = string.Format(CultureInfo.InvariantCulture, QueryUriTemplate, LogAnalyticsApiVersion, _workspaceId);
            string authority = string.Format(CultureInfo.InvariantCulture, AuthenticationAuthorityTemplate, _aadTenant);

            _authenticationContext = new AuthenticationContext(authority);
            var cert = new X509Certificate2(Convert.FromBase64String(_appCertificate));

            _certificateAssertion = new ClientAssertionCertificate(_appId, cert);
        }
        public ClientKey(IClientAssertionCertificate clientCertificate, Authenticator authenticator)
        {
            this.Authenticator = authenticator;
            if (clientCertificate == null)
            {
                throw new ArgumentNullException(nameof(clientCertificate));
            }
            this.Certificate = clientCertificate;

            this.ClientId      = clientCertificate.ClientId;
            this.HasCredential = true;
        }
        public ClientAssertion Sign(IClientAssertionCertificate credential)
        {
            // Base64Url encoded header and claims
            string token = this.Encode(credential);

            // Length check before sign
            if (MaxTokenLength < token.Length)
            {
                throw new AdalException(AdalError.EncodedTokenTooLong);
            }

            return(new ClientAssertion(this.payload.Issuer, string.Concat(token, ".", UrlEncodeSegment(credential.Sign(token)))));
        }
        private string Encode(IClientAssertionCertificate credential, bool sendX5C)
        {
            // Header segment
            string jsonHeader    = EncodeHeaderToJson(credential, sendX5C);
            string encodedHeader = EncodeSegment(jsonHeader);

            // Payload segment
            string jsonPayload = JsonHelper.EncodeToJson(this.payload);

            string encodedPayload = EncodeSegment(jsonPayload);

            return(string.Concat(encodedHeader, ".", encodedPayload));
        }
        public JsonWebToken(IClientAssertionCertificate certificate, string audience)
        {
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo   = validFrom + TimeSpan.FromSeconds(JsonWebTokenConstants.JwtToAadLifetimeInSeconds);

            this.payload = new JWTPayload
            {
                Audience      = audience,
                Issuer        = certificate.ClientId,
                ValidFrom     = ConvertToTimeT(validFrom),
                ValidTo       = ConvertToTimeT(validTo),
                Subject       = certificate.ClientId,
                JwtIdentifier = Guid.NewGuid().ToString()
            };
        }
Esempio n. 11
0
        private async Task <AuthenticationResult> AuthenticateFromClientAssertionCertificate(
            string resourceId,
            IClientAssertionCertificate certificate)
        {
            if (string.IsNullOrWhiteSpace(resourceId))
            {
                throw new ArgumentNullException(nameof(resourceId));
            }

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

            var authContext = new AuthenticationContext(this.authority);

            return(await authContext.AcquireTokenAsync(resourceId, certificate));
        }
 private static string EncodeHeaderToJson(IClientAssertionCertificate credential, bool sendX5C)
 {
     return(JsonHelper.EncodeToJson(new JWTHeaderWithCertificate(credential, sendX5C)));
 }
Esempio n. 13
0
 public async Task <AuthenticationResultProxy> AcquireTokenAsync(string resource, IClientAssertionCertificate clientCertificate, string userAssertion)
 {
     return(await RunTaskAsync(this.context.AcquireTokenAsync(resource, clientCertificate, (userAssertion == null) ? null : new UserAssertion(userAssertion))));
 }
Esempio n. 14
0
 public async Task <AuthenticationResultProxy> AcquireTokenAsync(string resource, IClientAssertionCertificate certificate)
 {
     return(await RunTaskAsync(this.context.AcquireTokenAsync(resource, certificate)));
 }
Esempio n. 15
0
 public async Task <AuthenticationResultProxy> AcquireTokenSilentAsync(string resource, IClientAssertionCertificate clientCertificate, UserIdentifier userId)
 {
     return(await RunTaskAsync(this.context.AcquireTokenSilentAsync(resource, clientCertificate, userId)));
 }
        public ClientAssertion Sign(IClientAssertionCertificate credential)
        {
            // Base64Url encoded header and claims
            string token = this.Encode(credential);     

            // Length check before sign
            if (MaxTokenLength < token.Length)
            {
                throw new MsalException(MsalError.EncodedTokenTooLong);
            }

            return new ClientAssertion(string.Concat(token, ".", UrlEncodeSegment(credential.Sign(token))));
        }
Esempio n. 17
0
        /// <summary>
        /// Acquires security token without asking for user credential.
        /// </summary>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
        /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
        /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="T:Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" />.Any.</param>
        /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
        public async Task <IAuthenticationResultWrapper> AcquireTokenSilentAsync(string resource, IClientAssertionCertificate clientCertificate, UserIdentifier userId)
        {
            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException(nameof(resource));
            }

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

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

            var result = await this.Context.AcquireTokenSilentAsync(resource, clientCertificate, userId).ConfigureAwait(false);

            return(new AuthenticationResultWrapper(result));
        }
Esempio n. 18
0
 /// <summary>
 /// Constructor to create Secret with client id and secret
 /// </summary>
 /// <param name="certificate">Secret of the client requesting the token.</param>
 public ClientCredential(IClientAssertionCertificate certificate)
 {
     this.Certificate = certificate;
 }
 public JWTHeader(IClientAssertionCertificate credential)
 {
     this.Credential = credential;
 }
Esempio n. 20
0
 public async Task <AuthenticationResultProxy> AcquireTokenByAuthorizationCodeAsync(string authorizationCode, Uri redirectUri, IClientAssertionCertificate certificate)
 {
     return(await RunTaskAsync(this.context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, redirectUri, certificate)));
 }
 /// <summary>
 /// Acquires security token from the authority.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns>
 public async Task <AuthenticationResult> AcquireTokenAsync(string resource, IClientAssertionCertificate clientCertificate)
 {
     return(await this.AcquireTokenForClientCommonAsync(resource, new ClientKey(clientCertificate, this.Authenticator)).ConfigureAwait(false));
 }
 public Task <AppAuthenticationResult> AcquireTokenAsync(string authority, string resource, IClientAssertionCertificate clientCertificate)
 {
     return(AcquireTokenAsync());
 }
 /// <summary>
 /// Acquires an access token from the authority on behalf of a user. It requires using a user token previously received.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="userAssertion">The user assertion (token) to use for token acquisition.</param>
 /// <returns>It contains Access Token and the Access Token's expiration time.</returns>
 public async Task <AuthenticationResult> AcquireTokenAsync(string resource, IClientAssertionCertificate clientCertificate, UserAssertion userAssertion)
 {
     return(await this.AcquireTokenOnBehalfCommonAsync(resource, new ClientKey(clientCertificate, this.Authenticator), userAssertion));
 }
 /// <summary>
 /// Constructor to create Secret with client id and secret
 /// </summary>
 /// <param name="certificate">Secret of the client requesting the token.</param>
 public ClientCredential(IClientAssertionCertificate certificate)
 {
     this.Certificate = certificate;
 }
 public CertificateAuthenticationProvider(IClientAssertionCertificate certificate, bool isCertRollOverEnabled)
 {
     this.certificate           = certificate;
     this.isCertRollOverEnabled = isCertRollOverEnabled;
 }
        private static string EncodeHeaderToJson(IClientAssertionCertificate credential)
        {
            JWTHeaderWithCertificate header = new JWTHeaderWithCertificate(credential);

            return(JsonHelper.EncodeToJson(header));
        }
Esempio n. 27
0
        /// <summary>
        /// Used to get authentication for client credentials flow using a client certificate.
        /// </summary>
        /// <param name="authority"></param>
        /// <param name="resource"></param>
        /// <param name="clientCertificate"></param>
        /// <returns></returns>
        public async Task <AppAuthenticationResult> AcquireTokenAsync(string authority, string resource, IClientAssertionCertificate clientCertificate)
        {
            var authenticationContext = GetAuthenticationContext(authority);
            var authResult            = await authenticationContext.AcquireTokenAsync(resource, clientCertificate, true).ConfigureAwait(false);

            return(AppAuthenticationResult.Create(authResult));
        }
 public JWTHeaderWithCertificate(IClientAssertionCertificate credential)
     : base(credential)
 {
 }
 private static string EncodeHeaderToJson(IClientAssertionCertificate credential)
 {
     JWTHeaderWithCertificate header = new JWTHeaderWithCertificate(credential);
     return JsonHelper.EncodeToJson(header);
 }
        private string Encode(IClientAssertionCertificate credential)
        {
            // Header segment
            string jsonHeader = EncodeHeaderToJson(credential);

            string encodedHeader = EncodeSegment(jsonHeader);

            // Payload segment
            string jsonPayload = JsonHelper.EncodeToJson(this.Payload);

            string encodedPayload = EncodeSegment(jsonPayload);

            return string.Concat(encodedHeader, ".", encodedPayload);
        }
 public JWTHeader(IClientAssertionCertificate credential)
 {
     this.Credential = credential;
 }
 /// <summary>
 /// Acquires security token from the authority using an authorization code previously received.
 /// This method does not lookup token cache, but stores the result in it, so it can be looked up using other methods such as <see cref="AuthenticationContext.AcquireTokenSilentAsync(string, string, UserIdentifier)"/>.
 /// </summary>
 /// <param name="authorizationCode">The authorization code received from service authorization endpoint.</param>
 /// <param name="redirectUri">The redirect address used for obtaining authorization code.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token. It can be null if provided earlier to acquire authorizationCode.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns>
 public async Task <AuthenticationResult> AcquireTokenByAuthorizationCodeAsync(string authorizationCode, Uri redirectUri, IClientAssertionCertificate clientCertificate, string resource)
 {
     return(await this.AcquireTokenByAuthorizationCodeCommonAsync(authorizationCode, redirectUri, new ClientKey(clientCertificate, this.Authenticator), resource));
 }
 public JWTHeaderWithCertificate(IClientAssertionCertificate credential)
     : base(credential)
 {
 }
 /// <summary>
 /// Acquires security token without asking for user credential.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
 /// <param name="userId">Identifier of the user token is requested for. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time. If acquiring token without user credential is not possible, the method throws AdalException.</returns>
 public async Task <AuthenticationResult> AcquireTokenSilentAsync(string resource, IClientAssertionCertificate clientCertificate, UserIdentifier userId)
 {
     return(await this.AcquireTokenSilentCommonAsync(resource, new ClientKey(clientCertificate, this.Authenticator), userId, null));
 }
Esempio n. 35
0
        /// <summary>
        /// Acquires security token from the authority using an authorization code previously received.
        /// This method does not lookup token cache, but stores the result in it, so it can be looked up using other methods such as <see cref="M:Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenSilentAsync(System.String,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier)" />.
        /// </summary>
        /// <param name="authorizationCode">The authorization code received from service authorization endpoint.</param>
        /// <param name="redirectUri">The redirect address used for obtaining authorization code.</param>
        /// <param name="clientCertificate">The client certificate to use for token acquisition.</param>
        /// <param name="resource">Identifier of the target resource that is the recipient of the requested token. It can be null if provided earlier to acquire authorizationCode.</param>
        /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns>
        public async Task <IAuthenticationResultWrapper> AcquireTokenByAuthorizationCodeAsync(string authorizationCode, Uri redirectUri, IClientAssertionCertificate clientCertificate, string resource)
        {
            if (string.IsNullOrWhiteSpace(authorizationCode))
            {
                throw new ArgumentNullException(nameof(authorizationCode));
            }

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

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

            if (string.IsNullOrWhiteSpace(resource))
            {
                throw new ArgumentNullException(nameof(resource));
            }

            var result = await this.Context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, redirectUri, clientCertificate, resource).ConfigureAwait(false);

            return(new AuthenticationResultWrapper(result));
        }