예제 #1
0
        public static async Task <AuthenticationHeaderValue> GetAuthHeaderValueAsync(
            this ILocalStorageService localStorage)
        {
            string accessToken = await localStorage.GetAccessTokenAsync();

            return(new AuthenticationHeaderValue("Bearer", accessToken));
        }
예제 #2
0
        public async Task <ClaimsPrincipal> GetAuthenticatedUserAsync()
        {
            string encodedToken = await _localStorage.GetAccessTokenAsync();

            if (string.IsNullOrWhiteSpace(encodedToken))
            {
                return(null);
            }

            var accessToken = new JwtSecurityToken(encodedToken);

            if (!VerifyTokenLifetime(accessToken))
            {
                string accessTokenString = await GetNewAccessTokenAsync();

                if (accessTokenString != null)
                {
                    await _localStorage.SetAccessTokenAsync(accessTokenString);

                    accessToken = new JwtSecurityToken(accessTokenString);
                }
                else
                {
                    return(null);
                }
            }


            string userId   = accessToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
            string userName = accessToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

            if (userId != null && userName != null)
            {
                var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userId),
                    new Claim(ClaimTypes.Name, userName),
                }, "Bearer");

                return(new ClaimsPrincipal(identity));
            }
            else
            {
                throw new Exception("Invalid access token received");
            }
        }