Example #1
0
        public HackneyTokenDomain ValidateHackneyJwtToken(HackneyTokenDomain hackneyTokenDomain)
        {
            try
            {
                var timeIssued = DateTimeOffset.FromUnixTimeSeconds(hackneyTokenDomain.Iat);

                // If not hackney email, fail
                if (!hackneyTokenDomain.Email.Contains("@hackney.gov.uk"))
                {
                    throw new Exception("Invalid token");
                }

                // By default the token expires in one week. If more or less then reject token
                if ((timeIssued.AddDays(7).AddMinutes(10) < DateTimeOffset.UtcNow) || (timeIssued.AddDays(7) > DateTimeOffset.UtcNow.AddDays(7).AddMinutes(10)))
                {
                    throw new Exception("Invalid token");
                }

                return(hackneyTokenDomain);
            }
            catch (Exception e)
            {
                if (Debugger.IsAttached)
                {
                    Console.WriteLine(e);
                }
                throw new ApiException("Invalid token. Please check and try again", StatusCodes.Status401Unauthorized);
            }
        }
Example #2
0
        public HackneyTokenDomain ValidateHackneyJwtToken(string hackneyToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                tokenHandler.ValidateToken(hackneyToken, new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = false,
                    ValidateAudience         = false,
                    ValidIssuer        = "Hackney",
                    IssuerSigningKey   = null,
                    ValidateLifetime   = false,
                    SignatureValidator = delegate(string token, TokenValidationParameters parameters)
                    {
                        var jwt = new JwtSecurityToken(token);

                        return(jwt);
                    },
                    // set clock skew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = Debugger.IsAttached ? TimeSpan.Zero : TimeSpan.FromMinutes(10)
                }, out var validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;

                var hackneyAuthDomain = new HackneyTokenDomain
                {
                    Sub    = jwtToken.Claims.First(x => x.Type == "sub").Value,
                    Email  = jwtToken.Claims.First(x => x.Type == "email").Value,
                    Iss    = jwtToken.Claims.First(x => x.Type == "iss").Value,
                    Name   = jwtToken.Claims.First(x => x.Type == "name").Value,
                    Groups = jwtToken.Claims.Where(x => x.Type == "groups").Select(x => x.Value).ToList(),
                    Iat    = int.Parse(jwtToken.Claims.First(x => x.Type == "iat").Value)
                };

                switch (Debugger.IsAttached)
                {
                // Check if id token is expired in production
                case false:
                {
                    var timeIssued = DateTimeOffset.FromUnixTimeSeconds(hackneyAuthDomain.Iat);

                    // If not hackney email, fail
                    if (!hackneyAuthDomain.Email.Contains("@hackney.gov.uk"))
                    {
                        throw new Exception("Invalid token");
                    }

                    // By default the token expires in one week. If more or less then reject token
                    if ((timeIssued.AddDays(7).AddMinutes(10) < DateTimeOffset.UtcNow) || (timeIssued.AddDays(7) > DateTimeOffset.UtcNow.AddDays(7).AddMinutes(10)))
                    {
                        throw new Exception("Invalid token");
                    }

                    break;
                }
                }

                return(hackneyAuthDomain);
            }
            catch (Exception e)
            {
                if (Debugger.IsAttached)
                {
                    Console.WriteLine(e);
                }
                throw new ApiException("Invalid token. Please check and try again", StatusCodes.Status401Unauthorized);
            }
        }
Example #3
0
        public async Task <AppUserDomain> GetOrCreateUser(HackneyTokenDomain hackneyTokenDomain)
        {
            var user = await _userManager.FindByEmailAsync(hackneyTokenDomain.Email).ConfigureAwait(false);

            switch (user)
            {
            case null:
            {
                var userEntity = new User
                {
                    Email                = hackneyTokenDomain.Email,
                    EmailConfirmed       = false,
                    LockoutEnabled       = false,
                    NormalizedEmail      = hackneyTokenDomain.Email.ToUpperInvariant(),
                    NormalizedUserName   = hackneyTokenDomain.Email.ToUpperInvariant(),
                    PasswordHash         = null,
                    PhoneNumber          = null,
                    PhoneNumberConfirmed = false,
                    TwoFactorEnabled     = false,
                    UserName             = hackneyTokenDomain.Email,
                    Name = hackneyTokenDomain.Name
                };

                var result = await _userManager.CreateAsync(userEntity).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    var defaultRoles = new List <string> {
                        RolesEnum.Broker.GetDisplayName()
                    };
                    var newUserRoles = new List <string>();
                    foreach (var userRole in defaultRoles)
                    {
                        if (await _roleManager.RoleExistsAsync(userRole).ConfigureAwait(false))
                        {
                            newUserRoles.Add(userRole);
                        }
                    }

                    if (newUserRoles.Count > 0)
                    {
                        await _userManager.AddToRolesAsync(userEntity, newUserRoles).ConfigureAwait(false);
                    }

                    return(userEntity?.ToDomain());
                }

                var validationErrorCollection = new ValidationErrorCollection();

                foreach (var error in result.Errors)
                {
                    validationErrorCollection.Add(new ValidationError
                        {
                            Message   = error.Description,
                            ControlID = error.Code,
                            ID        = error.Code
                        });
                }

                throw new ApiException($"User creation failed", (int)StatusCodes.Status400BadRequest,
                                       validationErrorCollection);
            }
            }

            return(user.ToDomain());
        }