Ejemplo n.º 1
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
                }
            });
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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));
        }
Ejemplo n.º 4
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)));
        }
Ejemplo n.º 5
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);
        }
        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"))));
        }
        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"))));
        }
Ejemplo n.º 8
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()
        {
            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);
        }
        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"))));
        }
Ejemplo n.º 12
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"))));
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        public void JwtParser_GetClaims_ShouldReturn7Claims()
        {
            var claims = JwtParser.ParseClaimsFromJwt(token);

            Assert.AreEqual(7, claims.Count());
        }
Ejemplo n.º 15
0
    public static ClaimsPrincipal GetClaimsPrincipal(string jwt)
    {
        var userClaimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(jwt), "Fake Authentication"));

        return(userClaimPrincipal);
    }