public AccessTokenMiddleware(RequestDelegate nextDelegate,
                              IRepository <Connection, long> connectionRepository, AccessTokenValidator accessTokenValidator)
 {
     this.nextDelegate         = nextDelegate;
     this.connectionRepository = connectionRepository;
     this.accessTokenValidator = accessTokenValidator;
 }
Example #2
0
        async Task <HttpResponseMessage> Process()
        {
            // Extract an access token from the request and
            // validate it. The instance of 'AccessTokenValidator'
            // returned from ValidateAccessToken() method holds the
            // result of the access token validation.
            //
            // Note that ValidateAccessToken() can optionally take
            // 'requiredScopes' and 'requiredSubject' parameters
            // although they are not used in this example.
            AccessTokenValidator validator = await ValidateAccessToken();

            // If the access token is not valid.
            if (validator.IsValid == false)
            {
                // When 'IsValid' returns false, 'ErrorResponse'
                // holds an error response that should be returned
                // to the client application. The response complies
                // with RFC 6750 (The OAuth 2.0 Authorization
                // Framework: Bearer Token Usage).
                //
                // You can refer to 'IntrospectionResult' or
                // 'IntrospectionError' for more information.
                return(validator.ErrorResponse);
            }

            // The access token is valid, so it's okay for this
            // protected resource endpoint to return the requested
            // protected resource.

            // Generate a response specific to this protected
            // resource endpoint and return it to the client.
            return(BuildResponse());
        }
 public AccessTokenMiddleware(RequestDelegate nextDelegate, IRepository <Authorization, long> authorizationRepository,
                              AccessTokenValidator accessTokenValidator)
 {
     this.nextDelegate            = nextDelegate;
     this.authorizationRepository = authorizationRepository;
     this.accessTokenValidator    = accessTokenValidator;
 }
Example #4
0
        public void ValidateAsync_GarbageJwt_Throws()
        {
            var publicKeyProvider = new Mock <IPublicKeyProvider>(MockBehavior.Strict).Object;
            IAccessTokenValidator accessTokenValidator = new AccessTokenValidator(publicKeyProvider);

            Assert.Throws <ValidationException>(() =>
                                                accessTokenValidator.ValidateAsync("garbage").ConfigureAwait(false).GetAwaiter().GetResult()
                                                );
        }
Example #5
0
        private async Task RunTest(
            bool signJwt,
            DateTime jwtExpiry,
            Type expectedExceptionType = null
            )
        {
            string             keyId              = Guid.NewGuid().ToString();
            D2LSecurityToken   signingToken       = D2LSecurityTokenUtility.CreateActiveToken(id: keyId);
            SigningCredentials signingCredentials = null;

            if (signJwt)
            {
                signingCredentials = signingToken.GetSigningCredentials();
            }

            var jwtToken = new JwtSecurityToken(
                issuer: "someissuer",
                signingCredentials: signingCredentials,
                expires: jwtExpiry
                );

            var    tokenHandler  = new JwtSecurityTokenHandler();
            string serializedJwt = tokenHandler.WriteToken(jwtToken);

            IPublicKeyProvider publicKeyProvider = PublicKeyProviderMock.Create(
                m_jwksEndpoint,
                keyId,
                signingToken
                ).Object;

            IAccessTokenValidator tokenValidator = new AccessTokenValidator(
                publicKeyProvider
                );

            IAccessToken accessToken = null;
            Exception    exception   = null;

            try {
                accessToken = await tokenValidator.ValidateAsync(
                    accessToken : serializedJwt
                    ).ConfigureAwait(false);
            } catch (Exception e) {
                exception = e;
            }

            if (expectedExceptionType != null)
            {
                Assert.IsNull(accessToken, "Unexpected access token returned from validation");
                Assert.IsNotNull(exception, "Expected an exception but got null");
                Assert.AreEqual(expectedExceptionType, exception.GetType(), "Wrong exception type");
            }
            else
            {
                Assert.IsNotNull(accessToken, "Expected an access token but got none");
            }
        }
Example #6
0
        public string Confirm()
        {
            string query  = Request.RequestUri.ParseQueryString().Get("id");
            string email  = AesConfig.DecryptStringFromBytes_Aes(AccessTokenValidator.StringToByteArray(query));
            var    dbUser = (from m in db.Users
                             where m.Email == email
                             select m).FirstOrDefault();

            dbUser.Confirmed = 1;
            db.SaveChanges();
            return("You have successfully activated yout account");
        }
        public void BeforeEach()
        {
            serviceCollection = ServiceConfiguration.InitServiceCollection();
            provider          = ServiceConfiguration.BuildServiceProvider();

            configuration        = provider.GetRequiredService <IConfiguration>();
            connectionRepository = provider.GetRequiredService <IRepository <Connection, long> >();
            userRepository       = provider.GetRequiredService <IRepository <User, string> >();


            validator = provider.GetRequiredService <AccessTokenValidator>();

            controller     = provider.GetRequiredService <ConnectionController>();
            userController = provider.GetRequiredService <UserController>();
        }
Example #8
0
        /// <summary>
        /// Validate the access token. This method extracts an
        /// access token from the request and then validates the
        /// access token by calling <c>Validate()</c> method of
        /// <c>Authlete.Web.AccessTokenValidator</c>.
        /// </summary>
        ///
        /// <returns>
        /// An instance of <c>AccessTokenValidator</c> that holds
        /// the result of the access token validation. See the
        /// API document of
        /// <c><a href="https://authlete.github.io/authlete-csharp/class_authlete_1_1_web_1_1_access_token_validator.html">AccessTokenValidator</a></c>
        /// for details as to how to use <c>AccessTokenValidator</c>.
        /// </returns>
        ///
        /// <param name="requiredScopes">
        /// Scopes that the access token should cover. If a
        /// non-null value is given to this parameter, Authlete's
        /// <c>/api/auth/introspection</c> API checks whether the
        /// access token covers all the required scopes.
        /// </param>
        ///
        /// <param name="requiredSubject">
        /// Subject (= unique identifier of an end-user) that the
        /// access token should be associated with. If a non-null
        /// value is given to this parameter, Authlete's
        /// <c>/api/auth/introspection</c> API checks whether the
        /// access token is associated with the required subject.
        /// </param>
        public async Task <AccessTokenValidator> ValidateAccessToken(
            string[] requiredScopes = null,
            string requiredSubject  = null)
        {
            // Extract an access token from the request.
            string accessToken = ExtractAccessToken();

            // Create a validator to validate the access token.
            var validator = new AccessTokenValidator(API);

            // Validate the access token. As a result of this call,
            // some properties of 'validator' are set. For example,
            // the 'IsValid' property holds the validation result.
            await validator.Validate(
                accessToken, requiredScopes, requiredSubject);

            // Return the validator that holds the result of the
            // access token validation.
            return(validator);
        }
Example #9
0
        public void BeforeEach()
        {
            serviceCollection = ServiceConfiguration.InitServiceCollection();
            provider          = ServiceConfiguration.BuildServiceProvider();

            configuration           = provider.GetRequiredService <IConfiguration>();
            clientRepository        = provider.GetRequiredService <IRepository <Client, string> >();
            authorizationRepository = provider.GetRequiredService <IRepository <Authorization, long> >();
            connectionRepository    = provider.GetRequiredService <IRepository <Connection, long> >();
            accountRepository       = provider.GetRequiredService <IRepository <Account, string> >();


            validator = provider.GetRequiredService <AccessTokenValidator>();

            controller = provider.GetRequiredService <AuthorizationController>();

            client = clientRepository.Save(new Client {
                Name = "clientApp", Id = "d8g1fn"
            });
        }
 public LocalDepartmentPropertiesValuesStore(AccessToken token)
 {
     values       = new Dictionary <DepartmentPropertyInfo, PropertyStade>();
     validator    = new AccessTokenValidator(token);
     enableSecure = true;
 }
 private static bool IsValidAnonymousUser(NancyContext context, string issuer, string secretKey)
 {
     return(AccessTokenValidator.Validate(context, issuer, secretKey));
 }
 private static bool IsValidAuthenticatedUser(NancyContext context, string issuer, string secretKey)
 {
     return(AccessTokenValidator.Validate(context, issuer, secretKey) &&
            !string.IsNullOrWhiteSpace(context.CurrentUser != null ? context.CurrentUser.UserName : null));
 }
 public CustomizedAccessTokenValidator(AccessTokenValidator accessTokenValidator)
 {
     _accessTokenValidator = accessTokenValidator;
 }