예제 #1
0
        public void NotifyUserAuthentication(string token)
        {
            var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"));
            var authState         = Task.FromResult(new AuthenticationState(authenticatedUser));

            NotifyAuthenticationStateChanged(authState);
        }
예제 #2
0
        public IActionResult ConfirmEmail(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                Alert.Danger("Invalid token");
                return(View("Error"));
            }

            var parser        = new JwtParser();
            var verifiyResult = parser.VerifyEmailToken(token);

            if (!verifiyResult.IsValid)
            {
                Alert.Danger("InvalidToken");
                return(View("Error"));
            }

            if (!confirmUserEmail.Invoke(verifiyResult.UserId))
            {
                Alert.Danger("User not found or already confirmed");
                return(View("Error"));
            }

            Alert.Success("Email confirmed");
            return(RedirectToAction("Login", "Auth"));
        }
예제 #3
0
        public JsonResult AcquireToken(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorResult = ModelState.GetErrorModel();
                return(Json(errorResult));
            }

            if (!checkUserExist.Invoke(model.Email, model.Password))
            {
                ModelState.AddModelError("Email", "Authentication failed");
                var errorResult = ModelState.GetErrorModel();

                return(Json(errorResult));
            }

            var parser = new JwtParser();

            var userId       = getUserId.Invoke(model.Email);
            var listUserApps = getUserApps.Invoke(userId);
            var appId        = listUserApps.Any() ? listUserApps.FirstOrDefault().Id : 0;

            var acquireResult = parser.AcquireToken(model.Email, appId);
            var result        = new ResultModel <string>(acquireResult.Token);

            return(Json(result));
        }
예제 #4
0
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>(MagicStrings.Local_Token);

            if (token == null)
            {
                Console.WriteLine($"**** GetAuthState: no token");
                return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
            }
            var exp = JwtParser.ParseExpirationTimeFromJwt(token);

            if (exp < DateTime.Now)
            {
                Console.WriteLine($"**** GetAuthState: token expired  ==> user logged out");
                await _localStorage.RemoveItemAsync(MagicStrings.Local_Token);

                return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
            }
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
            var principal = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token),
                                                                   "jwtAuthType"));

            Console.WriteLine($"**** GetAuthState: authenticated: {principal.Identity.IsAuthenticated}");
            return(new AuthenticationState(principal));
        }
예제 #5
0
        protected override async Task OnInitializedAsync()
        {
            base.OnInitialized();
            await Task.Delay(2000);

            var loggedinUser = (await AuthenticationStateTask).User;

            if (loggedinUser.IsInRole("Admin"))
            {
                Console.WriteLine($"User {loggedinUser.Identity.Name} is in role admin");
            }
            //var user = await LocalStorage.GetItemAsync<UserDto>(MagicStrings.Local_UserDetails);
            var token = await LocalStorage.GetItemAsync <string>(MagicStrings.Local_Token);

            var id   = JwtParser.ParseIdFromJwt(token);
            var user = await AuthenticationApiService.GetUserAsync(id);

            AuthenticatedUser = new UserDetailsDto();
            MiniMapper.CopyProperties(AuthenticatedUser, user);
            AuthenticatedUser.Role = JwtParser.ParseRolesFromJwt(token).FirstOrDefault();
            FormUser = new UserDetailsDto();
            MiniMapper.CopyProperties(FormUser, AuthenticatedUser);
            EditContext = new EditContext(FormUser);
            EditContext.OnFieldChanged += EditContext_OnFieldChanged;
        }
예제 #6
0
        internal static ClaimsPrincipal GetAuthenticatedUser(string token)
        {
            var      claims = JwtParser.ParseClaimsFromJwt(token);
            DateTime utcNow = DateTime.UtcNow;
            // Checks the nbf field of the token
            var notValidBefore = claims.Where(x => x.Type.Equals("nbf")).FirstOrDefault();

            if (notValidBefore is not null)
            {
                var datetime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(notValidBefore.Value));
                if (datetime.UtcDateTime > utcNow)
                {
                    return(new ClaimsPrincipal());
                }
            }
            // Checks the exp field of the token
            var expiry = claims.Where(claim => claim.Type.Equals("exp")).FirstOrDefault();

            if (expiry is not null)
            {
                // The exp field is in Unix time
                var datetime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expiry.Value));
                if (datetime.UtcDateTime <= utcNow)
                {
                    return(new ClaimsPrincipal());
                }
            }
            return(new ClaimsPrincipal(new ClaimsIdentity(claims, Constants.AUTH_TYPE)));
        }
예제 #7
0
        private async Task <SavedToken> ParseToken(LoginResult lr)
        {
            if (string.IsNullOrWhiteSpace(lr.Token))
            {
                return(new SavedToken());
            }
            var tokenExpired = IsTokenExpired(lr.ExpirationDate);

            if (tokenExpired)
            {
                await MarkUserAsLoggedOut();

                return(new SavedToken());
            }
            var    claims = JwtParser.ParseClaimsFromJwt(lr.Token);
            string userId = claims.Where(x => x.Type == "nameid").Select(x => x.Value).FirstOrDefault();

            return(new SavedToken()
            {
                Claims = claims,
                SavedLR = new LoginResult()
                {
                    UserId = userId,
                    Token = lr.Token,
                    ExpirationDate = lr.ExpirationDate
                }
            });
        }
예제 #8
0
        public void AcquireEmailConfirmationToken_ForValidInput_ReturnsCorrectToken()
        {
            var parser = new JwtParser();

            AcquireTokenModel tokenModel = parser.AcquireEmailConfirmationToken("*****@*****.**", 1);

            Assert.NotNull(tokenModel.Token);
        }
예제 #9
0
        public void AcquireEmailConfirmationToken_ForInvalidInput_ReturnsNull()
        {
            var parser = new JwtParser();

            AcquireTokenModel tokenModel = parser.AcquireEmailConfirmationToken(null, 0);

            Assert.Null(tokenModel);
        }
예제 #10
0
        public void NotifyUserLoggedIn(string token)
        {
            var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token),
                                                                           "jwtAuthType"));
            var authState = Task.FromResult(new AuthenticationState(authenticatedUser));

            Console.WriteLine($"**** NotifyUserLoggedIn: authenticated: {authenticatedUser.Identity.Name}");
            NotifyAuthenticationStateChanged(authState);
        }
예제 #11
0
        public void Verify_ForFreshToken_ReturnsOk()
        {
            var parser = new JwtParser();
            AcquireTokenModel tokenModel = parser.AcquireToken("*****@*****.**", 1);

            VerifyResultModel result = parser.Verify(tokenModel.Token);

            Assert.Equal(true, result.IsValid);
            Assert.NotNull(result.ExpiryDate);
        }
예제 #12
0
        public void Verify_ForExpiredToken_ReturnsError()
        {
            var    parser = new JwtParser();
            string token  = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InJhZmFsLmdyYWR6aWVAZmluZ28ucGwiLCJpc3MiOiJMZWduaWNhSVQiLCJBcHBJZCI6IjEiLCJuYmYiOjE0ODE3MTc0MTcsImV4cCI6MTQ4MTcyMTAxNywiaWF0IjoxNDgxNzE3NDE3fQ.ZPzu-eaoaY7CxyQmJwvfk18vd9sO5guOwbfjsKK1Qcg";

            VerifyResultModel result = parser.Verify(token);

            Assert.Equal(false, result.IsValid);
            Assert.Equal(null, result.ExpiryDate);
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>("authToken");

            if (string.IsNullOrWhiteSpace(token))
            {
                return(_anonymous);
            }
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"))));
        }
예제 #14
0
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>(LocalStorageKey.AuthToken.ToString());

            if (string.IsNullOrWhiteSpace(token))
            {
                return(_anonymous);
            }

            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"))));
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>(SD.Local_Token);

            if (token == null)
            {
                return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
            }
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"))));
        }
        /*
         * [Fact]
         * public void When_Passing_AuthorizationParameterWithoutOpenIdScope_Then_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "login",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "email"
         *  };
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, null));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidScope));
         *  Assert.True(exception.Message.Equals(string.Format(ErrorDescriptions.TheScopesNeedToBeSpecified, Core.Constants.StandardScopes.OpenId.Name)));
         *  Assert.True(exception.State.Equals(state));
         * }
         *
         * [Fact]
         * public void When_Passing_AuthorizationRequestWithMissingResponseType_Then_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "login",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid"
         *  };
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, null));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(string.Format(ErrorDescriptions.MissingParameter
         *      , Core.Constants.StandardAuthorizationRequestParameterNames.ResponseTypeName)));
         *  Assert.True(exception.State.Equals(state));
         * }
         *
         * [Fact]
         * public void When_Passing_AuthorizationRequestWithNotSupportedResponseType_Then_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "login",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code"
         *  };
         *
         *  // ACT
         *  var client = FakeFactories.FakeDataSource.Clients.FirstOrDefault(c => c.ClientId == clientId);
         *  Assert.NotNull(client);
         *  client.ResponseTypes.Remove(ResponseType.code);
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, null));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(string.Format(ErrorDescriptions.TheClientDoesntSupportTheResponseType
         *      , clientId, "code")));
         *  Assert.True(exception.State.Equals(state));
         * }
         *
         * [Fact]
         * public void When_TryingToByPassLoginAndConsentScreen_But_UserIsNotAuthenticated_Then_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "none",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code"
         *  };
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, null));
         *  Assert.True(exception.Code.Equals(ErrorCodes.LoginRequiredCode));
         *  Assert.True(exception.Message.Equals(ErrorDescriptions.TheUserNeedsToBeAuthenticated));
         *  Assert.True(exception.State.Equals(state));
         * }
         *
         * [Fact]
         * public void When_TryingToByPassLoginAndConsentScreen_But_TheUserDidntGiveHisConsent_Then_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "none",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code"
         *  };
         *
         *  var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity("fake"));
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InteractionRequiredCode));
         *  Assert.True(exception.Message.Equals(ErrorDescriptions.TheUserNeedsToGiveHisConsent));
         *  Assert.True(exception.State.Equals(state));
         * }
         *
         * [Fact]
         * public void When_Passing_A_NotValid_IdentityTokenHint_Parameter_Then_An_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string subject = "*****@*****.**";
         *  const string redirectUrl = "http://localhost";
         *  FakeFactories.FakeDataSource.Consents.Add(new Consent
         *  {
         *      ResourceOwner = new ResourceOwner
         *      {
         *          Id = subject
         *      },
         *      GrantedScopes = new List<Scope>
         *      {
         *          new Scope
         *          {
         *              Name = "openid"
         *          }
         *      },
         *      Client = FakeFactories.FakeDataSource.Clients.First()
         *  });
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      Prompt = "none",
         *      IdTokenHint = "invalid identity token hint"
         *  };
         *
         *  var claims = new List<Claim>
         *  {
         *      new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject)
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *
         *  // ACT
         *  var exception = Assert.Throws<IdentityServerExceptionWithState>(() => _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(ErrorDescriptions.TheIdTokenHintParameterIsNotAValidToken));
         * }
         *
         * [Fact]
         * public void When_Passing_An_IdentityToken_Valid_ForWrongAudience_Then_An_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string subject = "*****@*****.**";
         *  const string redirectUrl = "http://localhost";
         *  FakeFactories.FakeDataSource.Consents.Add(new Consent
         *  {
         *      ResourceOwner = new ResourceOwner
         *      {
         *          Id = subject
         *      },
         *      GrantedScopes = new List<Scope>
         *      {
         *          new Scope
         *          {
         *              Name = "openid"
         *          }
         *      },
         *      Client = FakeFactories.FakeDataSource.Clients.First()
         *  });
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      Prompt = "none",
         *  };
         *
         *  var subjectClaim = new Claim(Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject);
         *  var claims = new List<Claim>
         *  {
         *      subjectClaim
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *  var jwtPayload = new JwsPayload
         *  {
         *      {
         *          subjectClaim.Type, subjectClaim.Value
         *      }
         *  };
         *
         *  authorizationParameter.IdTokenHint = _jwtGenerator.Sign(jwtPayload, JwsAlg.RS256);
         *
         *  // ACT
         *  var exception = Assert.Throws<IdentityServerExceptionWithState>(() => _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(ErrorDescriptions.TheIdentityTokenDoesntContainSimpleIdentityServerAsAudience));
         * }
         *
         * [Fact]
         * public void When_Passing_An_IdentityToken_Different_From_The_Current_Authenticated_User_Then_An_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string subject = "*****@*****.**";
         *  const string issuerName = "audience";
         *  const string redirectUrl = "http://localhost";
         *  FakeFactories.FakeDataSource.Consents.Add(new Consent
         *  {
         *      ResourceOwner = new ResourceOwner
         *      {
         *          Id = subject
         *      },
         *      GrantedScopes = new List<Scope>
         *      {
         *          new Scope
         *          {
         *              Name = "openid"
         *          }
         *      },
         *      Client = FakeFactories.FakeDataSource.Clients.First()
         *  });
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      Prompt = "none",
         *  };
         *
         *  var subjectClaim = new Claim(Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject);
         *  var claims = new List<Claim>
         *  {
         *      subjectClaim
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *  var jwtPayload = new JwsPayload
         *  {
         *      {
         *          subjectClaim.Type, "wrong subjet"
         *      },
         *      {
         *          Jwt.Constants.StandardClaimNames.Audiences, new [] {  issuerName }
         *      }
         *  };
         *  _simpleIdentityServerConfiguratorStub.Setup(s => s.GetIssuerName()).Returns(issuerName);
         *  authorizationParameter.IdTokenHint = _jwtGenerator.Sign(jwtPayload, JwsAlg.RS256);
         *
         *  // ACT
         *  var exception = Assert.Throws<IdentityServerExceptionWithState>(() => _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(ErrorDescriptions.TheCurrentAuthenticatedUserDoesntMatchWithTheIdentityToken));
         * }
         *
         * [Fact]
         * public void When_Passing_Not_Supported_Prompts_Parameter_Then_An_Exception_Is_Thrown()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      Prompt = "select_account",
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code"
         *  };
         *
         *  var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity("fake"));
         *
         *  // ACT & ASSERTS
         *  var exception =
         *      Assert.Throws<IdentityServerExceptionWithState>(
         *          () => _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal));
         *  Assert.True(exception.Code.Equals(ErrorCodes.InvalidRequestCode));
         *  Assert.True(exception.Message.Equals(string.Format(ErrorDescriptions.ThePromptParameterIsNotSupported, "select_account")));
         *  Assert.True(exception.State.Equals(state));
         * }
         */
        #endregion

        /*
         #region TEST VALID SCENARIOS
         *
         * [Fact]
         * public void When_TryingToRequestAuthorization_But_TheUserConnectionValidityPeriodIsNotValid_Then_Redirect_To_The_Authentication_Screen()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  const long maxAge = 300;
         *  var currentDateTimeOffset = DateTimeOffset.UtcNow.ConvertToUnixTimestamp();
         *  currentDateTimeOffset -= maxAge + 100;
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      Prompt = "none",
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      MaxAge = 300
         *  };
         *
         *  var claims = new List<Claim>
         *  {
         *      new Claim(ClaimTypes.AuthenticationInstant, currentDateTimeOffset.ToString())
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.RedirectInstruction.Action.Equals(IdentityServerEndPoints.AuthenticateIndex));
         * }
         *
         * [Fact]
         * public void When_TryingToRequestAuthorization_But_TheUserIsNotAuthenticated_Then_Redirect_To_The_Authentication_Screen()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *  };
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, null);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.RedirectInstruction.Action.Equals(Core.Results.IdentityServerEndPoints.AuthenticateIndex));
         * }
         *
         * [Fact]
         * public void When_TryingToRequestAuthorization_And_TheUserIsAuthenticated_But_He_Didnt_Give_His_Consent_Then_Redirect_To_Consent_Screen()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *  };
         *
         *  var claimIdentity = new ClaimsIdentity("fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.RedirectInstruction.Action.Equals(Core.Results.IdentityServerEndPoints.ConsentIndex));
         * }
         *
         * [Fact]
         * public void When_TryingToRequestAuthorization_And_ExplicitySpecify_PromptConsent_But_The_User_IsNotAuthenticated_Then_Redirect_To_Consent_Screen()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      Prompt = "consent"
         *  };
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, null);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.RedirectInstruction.Action.Equals(Core.Results.IdentityServerEndPoints.AuthenticateIndex));
         * }
         *
         * [Fact]
         * public void When_TryingToRequestAuthorization_And_TheUserIsAuthenticated_And_He_Already_Gave_HisConsent_Then_The_AuthorizationCode_Is_Passed_To_The_Callback()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string subject = "*****@*****.**";
         *  const string redirectUrl = "http://localhost";
         *  FakeFactories.FakeDataSource.Consents.Add(new Consent
         *  {
         *      ResourceOwner = new ResourceOwner
         *      {
         *          Id = subject
         *      },
         *      GrantedScopes = new List<Scope>
         *      {
         *          new Scope
         *          {
         *              Name = "openid"
         *          }
         *      },
         *      Client = FakeFactories.FakeDataSource.Clients.First()
         *  });
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      Prompt = "none"
         *  };
         *
         *  var claims = new List<Claim>
         *  {
         *      new Claim(Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject)
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.Type.Equals(TypeActionResult.RedirectToCallBackUrl));
         *  Assert.True(result.RedirectInstruction.Parameters.Count().Equals(0));
         * }
         *
         #endregion
         *
         #region TEST THE LOGIN
         *
         * [Fact]
         * public void When_Executing_Correct_Authorization_Request_Then_Events_Are_Logged()
         * {
         *  // ARRANGE
         *  InitializeMockingObjects();
         *  const string state = "state";
         *  const string clientId = "MyBlog";
         *  const string redirectUrl = "http://localhost";
         *  const long maxAge = 300;
         *  var currentDateTimeOffset = DateTimeOffset.UtcNow.ConvertToUnixTimestamp();
         *  currentDateTimeOffset -= maxAge + 100;
         *  var authorizationParameter = new AuthorizationParameter
         *  {
         *      ClientId = clientId,
         *      State = state,
         *      Prompt = "none",
         *      RedirectUrl = redirectUrl,
         *      Scope = "openid",
         *      ResponseType = "code",
         *      MaxAge = 300
         *  };
         *
         *  var jsonAuthorizationParameter = authorizationParameter.SerializeWithJavascript();
         *
         *  var claims = new List<Claim>
         *  {
         *      new Claim(ClaimTypes.AuthenticationInstant, currentDateTimeOffset.ToString())
         *  };
         *  var claimIdentity = new ClaimsIdentity(claims, "fake");
         *  var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
         *
         *  // ACT
         *  var result = _processAuthorizationRequest.Process(authorizationParameter, claimsPrincipal);
         *
         *  // ASSERTS
         *  Assert.NotNull(result);
         *  Assert.True(result.RedirectInstruction.Action.Equals(IdentityServerEndPoints.AuthenticateIndex));
         *  _simpleIdentityServerEventSource.Verify(s => s.StartProcessingAuthorizationRequest(jsonAuthorizationParameter));
         *  _simpleIdentityServerEventSource.Verify(s => s.EndProcessingAuthorizationRequest(jsonAuthorizationParameter, "RedirectToAction", "AuthenticateIndex"));
         * }
         *
         #endregion
         */
        private void InitializeMockingObjects()
        {
            var clientValidator = new ClientValidator();

            _simpleIdentityServerConfiguratorStub = new Mock <IConfigurationService>();
            _oauthEventSource = new Mock <IOAuthEventSource>();
            var scopeRepository       = new Mock <IScopeRepository>();
            var clientRepository      = new Mock <IClientRepository>();
            var consentRepository     = new Mock <IConsentRepository>();
            var jsonWebKeyRepository  = new Mock <IJsonWebKeyRepository>();
            var parameterParserHelper = new ParameterParserHelper(scopeRepository.Object);
            var scopeValidator        = new ScopeValidator(parameterParserHelper);
            var actionResultFactory   = new ActionResultFactory();
            var consentHelper         = new ConsentHelper(consentRepository.Object, parameterParserHelper);
            var aesEncryptionHelper   = new AesEncryptionHelper();
            var jweHelper             = new JweHelper(aesEncryptionHelper);
            var jweParser             = new JweParser(jweHelper);
            var createJwsSignature    = new CreateJwsSignature(new CngKeySerializer());
            var jwsParser             = new JwsParser(createJwsSignature);
            var jsonWebKeyConverter   = new JsonWebKeyConverter();
            var httpClientFactory     = new Mock <IHttpClientFactory>();
            var jwtParser             = new JwtParser(
                jweParser,
                jwsParser,
                httpClientFactory.Object,
                clientRepository.Object,
                jsonWebKeyConverter,
                jsonWebKeyRepository.Object);
            var claimsMapping = new ClaimsMapping();
            var jwsGenerator  = new JwsGenerator(createJwsSignature);
            var jweGenerator  = new JweGenerator(jweHelper);

            _authenticationContextclassReferenceRepositoryStub = new Mock <IAuthenticationContextclassReferenceRepository>();
            _processAuthorizationRequest = new ProcessAuthorizationRequest(
                parameterParserHelper,
                clientValidator,
                scopeValidator,
                actionResultFactory,
                consentHelper,
                jwtParser,
                _simpleIdentityServerConfiguratorStub.Object,
                _oauthEventSource.Object,
                _authenticationContextclassReferenceRepositoryStub.Object);
            _jwtGenerator = new JwtGenerator(_simpleIdentityServerConfiguratorStub.Object,
                                             clientRepository.Object,
                                             clientValidator,
                                             jsonWebKeyRepository.Object,
                                             scopeRepository.Object,
                                             claimsMapping,
                                             parameterParserHelper,
                                             jwsGenerator,
                                             jweGenerator);
        }
예제 #17
0
        public void Configure(IApplicationBuilder app)
        {
            TokenValidationParameters tokenValidationParameters = new JwtParser().GetParameters();

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters,
                AuthenticationScheme      = JwtBearerDefaults.AuthenticationScheme,
            });
        }
예제 #18
0
        public void Verify_ForTokenParametersData()
        {
            var    parser = new JwtParser();
            string token  = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjEyM0B0ZXN0LnBsIiwiaXNzIjoiTGVnbmljYUlUIiwiYXBwSWQiOiIxIiwicm9sZSI6IlVzZXIiLCJuYmYiOjE0ODQxNDAwMjgsImV4cCI6MTQ4NDE0MDA4OCwiaWF0IjoxNDg0MTQwMDI4fQ.fZXSj3jZIQ8u2aoAzv6fDW0_c7BBb5oVr2oVDytnTek";

            VerifyResultModel result = parser.Verify(token, true);

            var email = result.Email;
            var appId = result.AppId;

            Assert.Equal("*****@*****.**", email);
            Assert.Equal(1, appId);
        }
예제 #19
0
        public JsonResult Verify(VerifyTokenModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorResult = ModelState.GetErrorModel();
                return(Json(errorResult));
            }

            var parser        = new JwtParser();
            var verifiyResult = parser.Verify(model.Token);
            var result        = new ResultModel <bool>(verifiyResult.IsValid);

            return(Json(result));
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            string token = await _localStorageService.GetItemAsync <string>("token");

            if (string.IsNullOrEmpty(token))
            {
                var anonymous = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()
                {
                }));
                return(anonymous);
            }
            var userClaimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "Fake Authentication"));
            var loginUser          = new AuthenticationState(userClaimPrincipal);

            return(loginUser);
        }
예제 #21
0
        public void AcquireEmailConfirmationToken_VerifyForTokenParametersData()
        {
            var parser = new JwtParser();
            AcquireTokenModel tokenModel = parser.AcquireEmailConfirmationToken("*****@*****.**", 1);

            var handler = new JwtSecurityTokenHandler();
            var param   = parser.GetParameters();
            JwtSecurityToken readToken = handler.ReadJwtToken(tokenModel.Token);

            var iss    = parser.GetClaim(readToken, "iss");
            var email  = parser.GetClaim(readToken, "email");
            var userId = parser.GetClaim(readToken, "userId");

            Assert.Equal(param.ValidIssuer, iss);
            Assert.Equal("*****@*****.**", email);
            Assert.Equal("1", userId);
        }
예제 #22
0
        public JsonResult SwitchApp(int appId)
        {
            var userId = getUserId.Invoke(LoggedUser.Email);

            if (!checkUserPermissionToApp.Invoke(userId, appId))
            {
                ModelState.AddModelError("AppId", "Permission denied");
                var errorResult = ModelState.GetErrorModel();

                return(Json(errorResult));
            }

            var parser        = new JwtParser();
            var acquireResult = parser.AcquireToken(LoggedUser.Email, appId);
            var result        = new ResultModel <string>(acquireResult.Token);

            return(Json(result));
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            //確認localstorage裡面是否有token
            string tokenInLocalStorage = await localStorageService.GetItemAsStringAsync("authToken");

            if (string.IsNullOrEmpty(tokenInLocalStorage))
            {
                //沒有的話,回傳匿名使用者
                return(anonymous);
            }

            //將token取出轉為claim
            var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);

            //在每次request的header中帶入bearer token
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage);

            //回傳帶有user claim的AuthenticationState物件
            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"))));
        }
        //AuthenticationState 에 의해 자동으로 사용되는 함수
        public async override Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>(SD.Local_Token);

            if (token == null)
            {
                //pass anonymous identity
                return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));

                //pass custom identity

                /*
                 * return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(
                 * new[] { new Claim(ClaimTypes.Name, "*****@*****.**"), new Claim(ClaimTypes.Role, "master") }, "jwtAuthType"
                 * )));
                 */
            }
            // putting token in header auto mode.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
            //pass roles
            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"))));
        }
예제 #25
0
        public void Verify_ForFreshToken_ReturnsCorrectExpiryDate()
        {
            var mockedDateTimeProvider = new Mock <IDateTimeProvider>();
            var dateFormat             = "yyyy-MM-dd HH:mm";
            var dateNow = DateTime.UtcNow;

            // we are using mocked IDateTimeProvider to make sure we are refering to same "now"
            mockedDateTimeProvider.Setup(p => p.GetNow()).Returns(dateNow);
            var parser = new JwtParser(mockedDateTimeProvider.Object);
            var dateNowFutureString = dateNow.AddDays(parser.GetExpiredDays()).ToString(dateFormat);

            AcquireTokenModel tokenModel       = parser.AcquireToken("*****@*****.**", 1);
            VerifyResultModel result           = parser.Verify(tokenModel.Token);
            string            expiryDateString = null;

            if (result.ExpiryDate != null)
            {
                expiryDateString = result.ExpiryDate.Value.ToString(dateFormat);
            }

            Assert.Equal(dateNowFutureString, expiryDateString);
        }
        public IEnumerable <Claim> GetClaims(HttpRequest req)
        {
            if (!req.Headers.ContainsKey("X-MS-TOKEN-AAD-ID-TOKEN"))
            {
                throw new ProblemJsonException(401, CalCrunch.Utils.Shared.DocumentationRoot + "missing-X-MS-TOKEN-AAD-ID-TOKEN",
                                               "Caller does not appear to be authenticated.",
                                               "You do not appear to be authenticated, therefore cannot check authorization for this resource.",
                                               req.Path);
            }

            var jwtToJson = new JwtParser(req.Headers["X-MS-TOKEN-AAD-ID-TOKEN"]);

            if (!jwtToJson.TryGetToken(out var token))
            {
                throw new ProblemJsonException(401, CalCrunch.Utils.Shared.DocumentationRoot + "invalid-X-MS-TOKEN-AAD-ID-TOKEN",
                                               "Could not parse jwt.",
                                               "The authentication token was invalid.",
                                               req.Path);
            }

            return(token.Claims);
        }
예제 #27
0
        private bool ValidateTokenExpiration(string token)
        {
            List <Claim> claims = JwtParser.ParseClaimsFromJwt(token).ToList();

            if (claims?.Count == 0)
            {
                return(false);
            }
            string expirationSeconds = claims.Where(_ => _.Type.ToLower() == "exp").Select(_ => _.Value).FirstOrDefault();

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

            var exprationDate = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(expirationSeconds));

            if (exprationDate < DateTime.UtcNow)
            {
                return(false);
            }
            return(true);
        }
예제 #28
0
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await _localStorage.GetItemAsync <string>("authToken");

            if (string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token))
            {
                return(_anonymous);
            }

            if (!string.IsNullOrEmpty(token) && token.Contains("null"))
            {
                await _localStorage.RemoveItemAsync("authToken");

                await _localStorage.RemoveItemAsync("refreshToken");

                NotifyUserLogout();
                return(_anonymous);
            }

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

            return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType"))));
        }
예제 #29
0
        public IActionResult ResendConfirmationEmail(ResendEmailConfirmationViewModel model)
        {
            var user = getUserDetails.Invoke(model.Email);

            if (user == null)
            {
                Alert.Danger("Something went wrong");
                return(View());
            }
            if (user.EmailConfirmedOn != null)
            {
                Alert.Danger("Email already confirmed");
                return(View());
            }

            var parser            = new JwtParser();
            var confirmationToken = parser.AcquireEmailConfirmationToken(model.Email, user.Id).Token;
            var callbackUrl       = Url.Action("ConfirmEmail", "Auth", new { token = confirmationToken }, Request.Scheme);

            emailService.SendEmailAsync(model.Email, "Confirm your account", callbackUrl).ConfigureAwait(false);

            Alert.Success("Check your inbox");
            return(View());
        }
예제 #30
0
        public IActionResult Register(RegisterViewModel model)
        {
            var userModel = new UserModel()
            {
                Email = model.Email, Password = model.Password, Name = model.Name
            };
            var userAddAction = addNewUser.Invoke(userModel);

            if (userAddAction == 0)
            {
                Alert.Danger("User Already exists");
                return(View());
            }
            var parser            = new JwtParser();
            var confirmationToken = parser.AcquireEmailConfirmationToken(model.Email, userAddAction).Token;
            var callbackUrl       = Url.Action("ConfirmEmail", "Auth", new { token = confirmationToken }, Request.Scheme);

            var emailConfirmView = RenderViewToString("ConfirmEmail", "", callbackUrl);

            emailService.SendEmailAsync(model.Email, "Confirm your account", emailConfirmView).ConfigureAwait(false);

            Alert.Success("Confirmation email has been sent to your email address");
            return(RedirectToAction("Login", "Auth"));
        }