Esempio n. 1
0
 public AccountController(EyadtakContext eyadtakDbContext, IJwt jwt, IEmail email, IConfiguration configuration)
 {
     _eyadtakDbContext = eyadtakDbContext;
     _jwt           = jwt;
     _email         = email;
     _configuration = configuration;
 }
Esempio n. 2
0
 public Authorize(IOptions <AuthSettings> settings, IJwt jwt, IAccountService service)
 {
     _settings = settings;
     _jwt      = jwt;
     _service  = service;
     _tokens   = new List <AuthorizeModel>();
 }
Esempio n. 3
0
 public AccountController(FacebookDataContext _myDbContext, IUserData _userData, IConfiguration _Configuration, IEmail _email, IJwt _jwt)
 {
     db            = _myDbContext;
     userData      = _userData;
     Configuration = _Configuration;
     email         = _email;
     jwt           = _jwt;
 }
Esempio n. 4
0
 public SignUpController(IUsuarioService usuarioService, ICustomMessage customMessasge, ICriptografia criptografia, IJwt jwt, IUnitOfWork uokOfWork)
 {
     _customMessasge = customMessasge;
     _criptografia   = criptografia;
     _jwt            = jwt;
     _uokOfWork      = uokOfWork;
     _usuarioService = usuarioService;
 }
Esempio n. 5
0
 public IdentityService(IConfiguration configuration, UserManager <AppUser> userManager,
                        SignInManager <AppUser> signInManager, IJwt jwt, ApplicationDbContext dbContext, IUserAccessor userAccessor)
 {
     _configuration = configuration;
     _userManager   = userManager;
     _signInManager = signInManager;
     _jwt           = jwt;
     _dbContext     = dbContext;
     _userAccessor  = userAccessor;
 }
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     INotificationHandler <DomainNotification> notifications,
     ILoggerFactory loggerFactory,
     IJwt jwt,
     IMediatorHandler mediator) : base(notifications, mediator)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _logger        = loggerFactory.CreateLogger <AccountController>();
     _jwt           = jwt;
 }
Esempio n. 7
0
        private static void AddByClaim(List <string> target, IJwt jwt, string claimName)
        {
            if (!jwt.Body.ContainsClaim(claimName))
            {
                return;
            }

            var value = jwt.Body.GetClaim(claimName).ToString();

            if (!string.IsNullOrEmpty(value))
            {
                target.Add(value);
            }
        }
        public bool IsValid(IJwt jwt)
        {
            if (jwt == null)
            {
                throw new ArgumentNullException(nameof(jwt));
            }

            if (!this.signatureValidator.IsValid(jwt))
            {
                return false;
            }

            // During parsing, the JWT is validated for expiration/lifetime, signature, and tampering
            throw new NotImplementedException();
        }
Esempio n. 9
0
        public bool IsValid(IJwt jwt)
        {
            if (jwt == null)
            {
                throw new ArgumentNullException(nameof(jwt));
            }

            if (!this.signatureValidator.IsValid(jwt))
            {
                return(false);
            }

            // During parsing, the JWT is validated for expiration/lifetime, signature, and tampering
            throw new NotImplementedException();
        }
Esempio n. 10
0
        private void ValidateExpectedClaims(IJwt jwt)
        {
            var expected = this.expectedClaims.Build().ToDictionary();
            var actual   = jwt.Body.ToDictionary();

            foreach (var claim in expected)
            {
                object actualValue = null;
                if (!actual.TryGetValue(claim.Key, out actualValue))
                {
                    throw new MissingClaimException($"The claim '{claim.Key}' was expected, but was not found in the JWT.");
                }

                // Special handling of integer comparisons. This fails for .Equals() because
                // one value may be type Int64 and the other type Int32 (for example).
                if (claim.Value.GetType() == typeof(long) ||
                    claim.Value.GetType() == typeof(int) ||
                    claim.Value.GetType() == typeof(short))
                {
                    long unboxedExpectedValue = default(long);
                    long unboxedActualValue   = default(long);

                    try
                    {
                        unboxedExpectedValue = Convert.ToInt64(claim.Value);
                        unboxedActualValue   = Convert.ToInt64(actualValue);
                    }
                    catch (Exception e)
                    {
                        throw new InvalidJwtException($"Could not decode the claim '{claim.Key}'.", e);
                    }

                    if (unboxedExpectedValue != unboxedActualValue)
                    {
                        throw new MismatchedClaimException($"The claim '{claim.Key}' should have a value of '{claim.Value}', but instead was '{actualValue}'.");
                    }

                    continue;
                }

                if (!claim.Value.Equals(actualValue))
                {
                    throw new MismatchedClaimException($"The claim '{claim.Key}' should have a value of '{claim.Value}', but instead was '{actualValue}'.");
                }
            }
        }
Esempio n. 11
0
        private bool IsValidJwt(string jwt, out IJwt parsedJwt)
        {
            parsedJwt = null;

            if (string.IsNullOrEmpty(jwt))
            {
                return(false);
            }

            try
            {
                parsedJwt = _client.NewJwtParser()
                            .SetSigningKey(_client.Configuration.Client.ApiKey.Secret, Encoding.UTF8)
                            .Parse(jwt);
                return(true);
            }
            catch (InvalidJwtException)
            {
                return(false);
            }
        }
Esempio n. 12
0
        public TokenRevoker AddToken(string jwt)
        {
            IJwt parsedJwt = null;

            if (!IsValidJwt(jwt, out parsedJwt))
            {
                return(this);
            }

            object rawTokenType = null;

            parsedJwt.Header.TryGetValue("stt", out rawTokenType);
            var tokenType = rawTokenType?.ToString();

            if (string.IsNullOrEmpty(tokenType))
            {
                // Assume it's an access token
                AddByClaim(_accessTokenIdsToDelete, parsedJwt, "jti");
                return(this);
            }

            if (tokenType.Equals("access", StringComparison.Ordinal))
            {
                AddByClaim(_accessTokenIdsToDelete, parsedJwt, "jti");

                // Add the accompanying refresh token, if it exists
                AddByClaim(_refreshTokenIdsToDelete, parsedJwt, "rti");
            }

            if (tokenType.Equals("refresh", StringComparison.Ordinal))
            {
                AddByClaim(_refreshTokenIdsToDelete, parsedJwt, "jti");
            }

            return(this);
        }
        private void ValidateExpectedClaims(IJwt jwt)
        {
            var expected = this.expectedClaims.Build().ToDictionary();
            var actual = jwt.Body.ToDictionary();

            foreach (var claim in expected)
            {
                object actualValue = null;
                if (!actual.TryGetValue(claim.Key, out actualValue))
                {
                    throw new MissingClaimException($"The claim '{claim.Key}' was expected, but was not found in the JWT.");
                }

                // Special handling of integer comparisons. This fails for .Equals() because
                // one value may be type Int64 and the other type Int32 (for example).
                if (claim.Value.GetType() == typeof(long)
                    || claim.Value.GetType() == typeof(int)
                    || claim.Value.GetType() == typeof(short))
                {
                    long unboxedExpectedValue = default(long);
                    long unboxedActualValue = default(long);

                    try
                    {
                        unboxedExpectedValue = Convert.ToInt64(claim.Value);
                        unboxedActualValue = Convert.ToInt64(actualValue);
                    }
                    catch (Exception e)
                    {
                        throw new InvalidJwtException($"Could not decode the claim '{claim.Key}'.", e);
                    }

                    if (unboxedExpectedValue != unboxedActualValue)
                    {
                        throw new MismatchedClaimException($"The claim '{claim.Key}' should have a value of '{claim.Value}', but instead was '{actualValue}'.");
                    }

                    continue;
                }

                if (!claim.Value.Equals(actualValue))
                {
                    throw new MismatchedClaimException($"The claim '{claim.Key}' should have a value of '{claim.Value}', but instead was '{actualValue}'.");
                }
            }
        }
 public bool IsValid(IJwt jwt)
     => this.IsValid(jwt.Base64Header, jwt.Base64Payload, jwt.Base64Digest);
Esempio n. 15
0
 public AuthorizedAbility(IJwt jwt, EyadtakContext eyadtakDbContext)
 {
     _jwt = jwt;
     _eyadtakDbContext = eyadtakDbContext;
 }
 private void VerifyCommon(IJwt jwt)
 {
     jwt.Body.Issuer.ShouldBe(FakeApiKeyId);
     jwt.Body.Subject.ShouldBe(FakeApplicationHref);
     jwt.Body.GetClaim("cb_uri").ShouldBe(FakeCallbackUri);
 }
        private async Task <IOauthGrantAuthenticationResult> ExchangeTokenAsync(IApplication application, IJwt jwt, CancellationToken cancellationToken)
        {
            try
            {
                var tokenExchangeAttempt = OauthRequests.NewIdSiteTokenAuthenticationRequest()
                                           .SetJwt(jwt.ToString())
                                           .Build();

                var grantResult = await application.NewIdSiteTokenAuthenticator()
                                  .AuthenticateAsync(tokenExchangeAttempt, cancellationToken);

                return(grantResult);
            }
            catch (ResourceException rex)
            {
                _logger.Warn(rex, source: nameof(ExchangeTokenAsync));
                throw; // json response
            }
        }
Esempio n. 18
0
 /// <summary>
 /// 注入jwt
 /// </summary>
 /// <param name="jwt"></param>
 public IdentityController(IJwt jwt)
 {
     _jwt = jwt;
 }
Esempio n. 19
0
 public AuthController(IAuth authService, IJwt jwtService, IUser userService)
 {
     _authService = authService;
     _jwtService  = jwtService;
     _userService = userService;
 }
        internal static void ThrowIfJwtSignatureInvalid(string jwtApiKey, IClientApiKey clientApiKey, IJwt jwt)
        {
            if (!clientApiKey.GetId().Equals(jwtApiKey, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new JwtSignatureException("The client used to sign the response is different than the one used in this DataStore.");
            }

            var signingKey = Encoding.UTF8.GetBytes(clientApiKey.GetSecret());
            if (!new JwtSignatureValidator(signingKey).IsValid(jwt))
            {
                throw new JwtSignatureException("The JWT signature is invalid.");
            }
        }
Esempio n. 21
0
 private void VerifyCommon(IJwt jwt)
 {
     jwt.Body.Issuer.ShouldBe(FakeApiKeyId);
     jwt.Body.Subject.ShouldBe(FakeApplicationHref);
     jwt.Body.GetClaim("cb_uri").ShouldBe(FakeCallbackUri);
 }
Esempio n. 22
0
 public AuthActionFilter(IConfiguration configration, IJwt jwt)
 {
     this._jwt = jwt;
     configration.GetSection("Jwt").Bind(_jwtConfig);
 }
        internal static void ThrowIfJwtSignatureInvalid(string jwtApiKey, IClientApiKey clientApiKey, IJwt jwt)
        {
            if (!clientApiKey.GetId().Equals(jwtApiKey, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new JwtSignatureException("The client used to sign the response is different than the one used in this DataStore.");
            }

            var signingKey = Encoding.UTF8.GetBytes(clientApiKey.GetSecret());

            if (!new JwtSignatureValidator(signingKey).IsValid(jwt))
            {
                throw new JwtSignatureException("The JWT signature is invalid.");
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Controller constructor
 /// </summary>
 public LoginController(ILoginService service, IJwt jwt)
 {
     _service = service;
     _jwt     = jwt;
 }
        private async Task <bool> HandleCallbackAsync(
            IOwinEnvironment context,
            IClient client,
            IApplication application,
            IJwt jwt,
            string nextPath,
            CancellationToken cancellationToken)
        {
            var isNewSubscriber = false;

            if (jwt.Body.ContainsClaim("isNewSub"))
            {
                isNewSubscriber = (bool)jwt.Body.GetClaim("isNewSub");
            }

            var status = jwt.Body.GetClaim("status").ToString();

            var isLogin        = status.Equals("authenticated", StringComparison.OrdinalIgnoreCase);
            var isLogout       = status.Equals("logout", StringComparison.OrdinalIgnoreCase);
            var isRegistration = isNewSubscriber || status.Equals("registered", StringComparison.OrdinalIgnoreCase);

            if (isRegistration)
            {
                var grantResult = await ExchangeTokenAsync(application, jwt, cancellationToken);

                var registrationExecutor = new RegisterExecutor(client, _configuration, _handlers, _logger);
                var account = await(await grantResult.GetAccessTokenAsync(cancellationToken)).GetAccountAsync(cancellationToken);
                await registrationExecutor.HandlePostRegistrationAsync(context, account, cancellationToken);

                return(await LoginAndRedirectAsync(
                           context,
                           client,
                           grantResult,
                           true,
                           nextPath,
                           cancellationToken));
            }

            if (isLogin)
            {
                var grantResult = await ExchangeTokenAsync(application, jwt, cancellationToken);

                return(await LoginAndRedirectAsync(
                           context,
                           client,
                           grantResult,
                           false,
                           nextPath,
                           cancellationToken));
            }

            if (isLogout)
            {
                var executor = new LogoutExecutor(client, _configuration, _handlers, _logger);

                await executor.HandleLogoutAsync(context, cancellationToken);

                await executor.HandleRedirectAsync(context);

                return(true);
            }

            // json response
            throw new ArgumentException($"Unknown assertion status '{status}'");
        }
Esempio n. 26
0
 public UserService(IJwt jwt, IPasswordHasher <BlogUser> passwordHasher, BlogDbContext context)
 {
     _jwt            = jwt;
     _passwordHasher = passwordHasher;
     _context        = context;
 }
 public UserHandler(AppDbContext context, IPasswordHashProvider passwordHashProvider, IJwt jwtService)
 {
     _context = context;
     _passwordHashProvider = passwordHashProvider;
     _jwtService           = jwtService;
 }
Esempio n. 28
0
 public UseJwtMiddleware(RequestDelegate next, IConfiguration configration, IJwt jwt)
 {
     _next = next;
     _jwt  = jwt;
     configration.GetSection("Jwt").Bind(_jwtConfig);
 }
 public AuthController(IJwt jwt, IUserAppService userAppService, ICacheManager redis)
 {
     this._jwt       = jwt;
     _userAppService = userAppService;
     _redis          = redis;
 }
Esempio n. 30
0
 public TokenController(IJwt _jwtRepository, ILogger <TokenController> _logger, IUser _userResearchRepository)
 {
     jwtRepository          = _jwtRepository;
     logger                 = _logger;
     userResearchRepository = _userResearchRepository;
 }
Esempio n. 31
0
 public AuthService(IEfRepository <ClientApi, Guid> clientApiRepository, IJwt jwt)
 {
     _clientApiRepository = clientApiRepository;
     _jwt = jwt;
 }
Esempio n. 32
0
 public AccountController(UniversityContext context, IJwt token)
 {
     jwt = token;
     db  = context;
 }
Esempio n. 33
0
 /// <summary>
 /// 注入jwt
 /// </summary>
 /// <param name="jwt"></param>
 public LoginController(IJwt jwt)
 {
     _jwt = jwt;
 }
Esempio n. 34
0
 public AuthController(IJwt jwt)
 {
     this._jwt = jwt;
 }
Esempio n. 35
0
 public AuthController(IJwt jwt, IConfiguration configration)
 {
     _jwt          = jwt;
     _configration = configration;
     projectInfos  = _configration.GetSection("ProjectInfo").Get <List <ProjectInfo> >();
 }