public void Decode_ShouldDecodeValidJWTokenPayload()
        {
            string validToken = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFBMjMyVEVTVCIsImFsZyI6IkhTMjU2In0.eyJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwibmFtZSI6IkpvaG4gRG9lIiwib2lkIjoiZTYwMmFkYTctNmVmZC00ZTE4LWE5NzktNjNjMDJiOWYzYzc2Iiwic2NwIjoiVXNlci5SZWFkQmFzaWMuQWxsIiwidGlkIjoiNmJjMTUzMzUtZTJiOC00YTlhLTg2ODMtYTUyYTI2YzhjNTgzIiwidW5pcXVlX25hbWUiOiJqb2huQGRvZS50ZXN0LmNvbSIsInVwbiI6ImpvaG5AZG9lLnRlc3QuY29tIn0.hf9xI5XYBjGec - 4n4_Kxj8Nd2YHBtihdevYhzFxbpXQ";

            JwtPayload decodedJwtPayload = JwtHelpers.DecodeToObject <JwtPayload>(validToken.Split('.')[1]);

            Assert.IsNotNull(decodedJwtPayload, "Unexpected jwt payload decoded.");
            Assert.IsNotNull(decodedJwtPayload.Oid, "Unexpected oid set decoded.");
        }
 public CartItemsController(
     JwtHelpers jwt,
     ICartItemRepository cartItemRepository,
     IMapper mapper
     )
 {
     _jwt = jwt;
     _cartItemRepository = cartItemRepository;
     _mapper             = mapper;
 }
Example #3
0
 public NotesController(
     JwtHelpers jwt,
     INoteRepository noteRepository,
     IMapper mapper
     )
 {
     _jwt            = jwt;
     _noteRepository = noteRepository;
     _mapper         = mapper;
 }
Example #4
0
 public UsersController(
     JwtHelpers jwt,
     IUserRepository userRepository,
     IMapper mapper
     )
 {
     _jwt            = jwt;
     _userRepository = userRepository;
     _mapper         = mapper;
 }
Example #5
0
 public ActionResult SignIn(AccountModel account)
 {
     if (account != null && ValidateUser(account))
     {
         var issuer = _configuration["Payload:Claims:Issuer"];
         var signKey = _configuration["Payload:Claims:SignKey"];
         var expires = _configuration.GetValue<int>("Payload:Claims:Expires"); // min
         var token = JwtHelpers.GenerateToken(issuer, signKey, account.Id, expires);
         var result = _domainController.SignIn(account, token);
         if (result != null)
         {
             return Ok(result);
         }
     }
     return NotFound("User not Exist or Pssword Error");   
 }
        public ActionResult <ResultModel> SignIn([FromBody] LoginViewModel login)
        {
            //https://blog.johnwu.cc/article/ironman-day09-asp-net-core-model-binding.html
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }


                _logger.Debug("登入驗證,並取得token");

                var issuer  = _settings.Value.Tokens.ValidIssuer;
                var signKey = _settings.Value.Tokens.IssuerSigningKey; // 請換成至少 16 字元以上的安全亂碼
                var expires = _settings.Value.Tokens.ValidExpires;     // 單位: 分鐘

                if (_ILoginService.ValidateUser(login))
                {
                    //List相當於mvc的index  api/Customers
                    var result = new ResultModel
                    {
                        Data      = JwtHelpers.GenerateToken(issuer, signKey, login.Username, expires),
                        IsSuccess = true
                    };

                    return(Ok(result));
                }
                else
                {
                    return(BadRequest(new ResultModel {
                        IsSuccess = false, Message = "失敗"
                    }));
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "");
                return(BadRequest(new ResultModel {
                    IsSuccess = false, Message = ""
                }));

                throw;
            }
        }
        /// <summary>
        /// Creats a <see cref="GraphUserAccount"/> object from a JWT access token.
        /// </summary>
        /// <param name="jwtAccessToken">JWT token to parse.</param>
        /// <returns></returns>
        private GraphUserAccount GetGraphUserAccount(string jwtAccessToken)
        {
            if (string.IsNullOrEmpty(jwtAccessToken))
            {
                return(null);
            }

            // Get jwt payload
            string[] jwtSegments    = jwtAccessToken.Split('.');
            string   payloadSegmant = jwtSegments.Count() == 1 ? jwtSegments.First() : jwtSegments[1];

            JwtPayload jwtPayload = JwtHelpers.DecodeToObject <JwtPayload>(payloadSegmant);

            return(new GraphUserAccount()
            {
                Email = jwtPayload.Upn,
                ObjectId = jwtPayload.Oid.ToString(),
                TenantId = jwtPayload.Oid.ToString()
            });
        }
        public ActionResult <string> SignIn(string username)
        {
            //TODO: 要放到Config中
            var issuer  = "JwtAuthDemo";
            var signKey = "1234567890123456";
            var expires = 30; //min
            var login   = new LoginViewModel()
            {
                Username = username
            };

            if (ValidateUser(login))
            {
                return(JwtHelpers.GenerateToken(issuer, signKey, login.Username, expires));
            }
            else
            {
                return(BadRequest());
            }
        }
Example #9
0
        public async Task <string> Login(LoginRequest request)
        {
            var account = await _accountsService.GetFullAccountByEmail(request.Email).ConfigureAwait(false);

            if (account == null)
            {
                throw new Exception("Login failed");
            }

            var valid = IntegraTestEncryption.IsCorrectPassword(request.Password, account.PasswordHash);

            if (!valid)
            {
                throw new Exception("Login failed");
            }

            return(JwtHelpers.CreateJwt(new JwtRequest()
            {
                UserEmail = account.Email,
                UserId = account.Id
            }));
        }
Example #10
0
        public IActionResult Token([FromBody] LoginInfo loginInfo)
        {
            //TODO: 要放到Config中
            var issuer  = _config["Payload:Claims:Issuer"];
            var signKey = _config["Payload:Claims:SignKey"];
            var expires = 30; //min
            int?userId  = _userService.ValidateUser(loginInfo);

            if (userId != null)
            {
                string token     = JwtHelpers.GenerateToken(issuer, signKey, loginInfo.account, expires);
                Token  viewmodel = new Token()
                {
                    token  = token,
                    userId = userId
                };
                return(Ok(viewmodel));
            }
            else
            {
                return(BadRequest("wrong account or password"));
            }
        }
Example #11
0
 public BaseTokenApiController(BaseContext dbContext, JwtHelpers jwtHelpers)
 {
     _dbContext  = _dbContext ?? dbContext;
     _jwtHelpers = _jwtHelpers ?? jwtHelpers;
 }
Example #12
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            AuthConfig authConfig = new AuthConfig {
                TenantId = TenantId
            };
            CancellationToken cancellationToken = CancellationToken.None;

            if (ParameterSetName == Constants.UserParameterSet)
            {
                // 2 mins timeout. 1 min < HTTP timeout.
                TimeSpan authTimeout        = new TimeSpan(0, 0, Constants.MaxDeviceCodeTimeOut);
                CancellationTokenSource cts = new CancellationTokenSource(authTimeout);
                cancellationToken = cts.Token;

                authConfig.AuthType = AuthenticationType.Delegated;
                authConfig.Scopes   = Scopes ?? new string[] { "User.Read" };
            }
            else
            {
                authConfig.AuthType = AuthenticationType.AppOnly;
                authConfig.ClientId = ClientId;
                authConfig.CertificateThumbprint = CertificateThumbprint;
                authConfig.CertificateName       = CertificateName;
            }

            try
            {
                // Gets a static instance of IAuthenticationProvider when the client app hasn't changed.
                IAuthenticationProvider authProvider      = AuthenticationHelpers.GetAuthProvider(authConfig);
                IClientApplicationBase  clientApplication = null;
                if (ParameterSetName == Constants.UserParameterSet)
                {
                    clientApplication = (authProvider as DeviceCodeProvider).ClientApplication;
                }
                else
                {
                    clientApplication = (authProvider as ClientCredentialProvider).ClientApplication;
                }

                // Incremental scope consent without re-instanciating the auth provider. We will use a static instance.
                GraphRequestContext graphRequestContext = new GraphRequestContext();
                graphRequestContext.CancellationToken = cancellationToken;
                graphRequestContext.MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                {
                    {
                        typeof(AuthenticationHandlerOption).ToString(),
                        new AuthenticationHandlerOption
                        {
                            AuthenticationProviderOption = new AuthenticationProviderOption
                            {
                                Scopes       = authConfig.Scopes,
                                ForceRefresh = ForceRefresh
                            }
                        }
                    }
                };

                // Trigger consent.
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
                httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext);
                authProvider.AuthenticateRequestAsync(httpRequestMessage).GetAwaiter().GetResult();

                var accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult();
                var account  = accounts.FirstOrDefault();

                JwtPayload jwtPayload = JwtHelpers.DecodeToObject <JwtPayload>(httpRequestMessage.Headers.Authorization?.Parameter);
                authConfig.Scopes   = jwtPayload?.Scp?.Split(' ') ?? jwtPayload?.Roles;
                authConfig.TenantId = jwtPayload?.Tid ?? account?.HomeAccountId?.TenantId;
                authConfig.AppName  = jwtPayload?.AppDisplayname;
                authConfig.Account  = jwtPayload?.Upn ?? account?.Username;

                // Save auth config to session state.
                SessionState.PSVariable.Set(Constants.GraphAuthConfigId, authConfig);
            }
            catch (AuthenticationException authEx)
            {
                if ((authEx.InnerException is TaskCanceledException) && cancellationToken.IsCancellationRequested)
                {
                    throw new Exception($"Device code terminal timed-out after {Constants.MaxDeviceCodeTimeOut} seconds. Please try again.");
                }
                else
                {
                    throw authEx.InnerException ?? authEx;
                }
            }
            catch (Exception ex)
            {
                throw ex.InnerException ?? ex;
            }

            WriteObject("Welcome To Microsoft Graph!");
        }
Example #13
0
 public AccountController(JwtHelpers jwt)
 {
     this.jwt = jwt;
 }
 public LoginController(ILogger <LoginController> logger, JwtHelpers jwtHelper)
 {
     this.logger    = logger;
     this.jwtHelper = jwtHelper;
 }
Example #15
0
 public TokenController(JwtHelpers jwt, PTCERPContext context)
 {
     this.jwt      = jwt;
     this._context = context;
 }
Example #16
0
 public JwtLoginController(JwtHelpers jwt)
 {
     this.jwt = jwt;
 }
Example #17
0
 public MemberController(IMemberService memberService, JwtHelpers jwt, IMapper mapper)
 {
     _memberService = memberService;
     _jwt           = jwt;
     _mapper        = mapper;
 }
Example #18
0
 public JwtController(JwtHelpers jwt)
 {
     _jwt = jwt;
 }
 public UserApiController(BaseContext dbContext, JwtHelpers jwtHelpers) : base(dbContext, jwtHelpers)
 {
 }
 public TokenController(JwtHelpers helper)
 {
     this.helper = helper;
 }
 public TokenController(JwtHelpers jwt, MiniChatRoomContext context)
 {
     this.jwt = jwt;
     _context = context;
 }
Example #22
0
 public LoginController(IUserService _UserIdentity, JwtHelpers _jwt)
 {
     this.UserIdentity = _UserIdentity;
     this.jwt          = _jwt;
 }
Example #23
0
 public MemberController(JwtHelpers jwt)
 {
     this._jwt = jwt;
 }
Example #24
0
 public TokenController(JwtHelpers jwt)
 {
     this.jwt = jwt;
 }
        public void Decode_ShouldThrowExceptionWhenInvalidJWTokenPayloadIsSet()
        {
            string validToken = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFBMjMyVEVTVCIsImFsZyI6IkhTMjU2In0.eyJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwibmFtZSI6IkpvaG4gRG9lIiwib2lkIjoiZTYwMmFkYTctNmVmZC00ZTE4LWE5NzktNjNjMDJiOWYzYzc2Iiwic2NwIjoiVXNlci5SZWFkQmFzaWMuQWxsIiwidGlkIjoiNmJjMTUzMzUtZTJiOC00YTlhLTg2ODMtYTUyYTI2YzhjNTgzIiwidW5pcXVlX25hbWUiOiJqb2huQGRvZS50ZXN0LmNvbSIsInVwbiI6ImpvaG5AZG9lLnRlc3QuY29tIn0.hf9xI5XYBjGec - 4n4_Kxj8Nd2YHBtihdevYhzFxbpXQ";

            AuthenticationException exception = Assert.ThrowsException <AuthenticationException>(() => JwtHelpers.DecodeToObject <JwtPayload>(validToken));

            Assert.AreEqual(exception.Error.Code, ErrorConstants.Codes.InvalidJWT);
            Assert.AreEqual(exception.Error.Message, ErrorConstants.Message.InvalidJWT);
        }
 public AccountController(ILogger <AccountController> logger, JwtHelpers jwt)
 {
     this.logger = logger;
     this.jwt    = jwt;
 }
Example #27
0
 public TokenController(JwtHelpers jwt, IHttpContextAccessor httpContextAccessor)
 {
     this.jwt             = jwt;
     _httpContextAccessor = httpContextAccessor;
 }
        /// <summary>
        /// Authenticates the client using the provided <see cref="IAuthContext"/>.
        /// </summary>
        /// <param name="authContext">The <see cref="IAuthContext"/> to authenticate.</param>
        /// <param name="forceRefresh">Whether or not to force refresh a token if one exists.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public static async Task <IAuthContext> AuthenticateAsync(IAuthContext authContext, bool forceRefresh, CancellationToken cancellationToken)
        {
            try
            {
                // Gets a static instance of IAuthenticationProvider when the client app hasn't changed.
                IAuthenticationProvider authProvider      = AuthenticationHelpers.GetAuthProvider(authContext);
                IClientApplicationBase  clientApplication = null;
                if (authContext.AuthType == AuthenticationType.Delegated)
                {
                    clientApplication = (authProvider as DeviceCodeProvider).ClientApplication;
                }
                if (authContext.AuthType == AuthenticationType.AppOnly)
                {
                    clientApplication = (authProvider as ClientCredentialProvider).ClientApplication;
                }

                // Incremental scope consent without re-instantiating the auth provider. We will use a static instance.
                GraphRequestContext graphRequestContext = new GraphRequestContext();
                graphRequestContext.CancellationToken = cancellationToken;
                graphRequestContext.MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                {
                    {
                        typeof(AuthenticationHandlerOption).ToString(),
                        new AuthenticationHandlerOption
                        {
                            AuthenticationProviderOption = new AuthenticationProviderOption
                            {
                                Scopes       = authContext.Scopes,
                                ForceRefresh = forceRefresh
                            }
                        }
                    }
                };

                // Trigger consent.
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
                httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext);
                await authProvider.AuthenticateRequestAsync(httpRequestMessage);

                IAccount account = null;
                if (clientApplication != null)
                {
                    // Only get accounts when we are using MSAL to get an access token.
                    IEnumerable <IAccount> accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult();
                    account = accounts.FirstOrDefault();
                }

                JwtHelpers.DecodeJWT(httpRequestMessage.Headers.Authorization?.Parameter, account, ref authContext);
                return(authContext);
            }
            catch (AuthenticationException authEx)
            {
                if ((authEx.InnerException is TaskCanceledException) && cancellationToken.IsCancellationRequested)
                {
                    // DeviceCodeTimeout
                    throw new Exception(string.Format(
                                            CultureInfo.CurrentCulture,
                                            ErrorConstants.Message.DeviceCodeTimeout,
                                            Constants.MaxDeviceCodeTimeOut));
                }
                else
                {
                    throw authEx.InnerException ?? authEx;
                }
            }
            catch (Exception ex)
            {
                throw ex.InnerException ?? ex;
            }
        }
Example #29
0
        /// <summary>
        /// Authenticates the client using the provided <see cref="IAuthContext"/>.
        /// </summary>
        /// <param name="authContext">The <see cref="IAuthContext"/> to authenticate.</param>
        /// <param name="forceRefresh">Whether or not to force refresh a token if one exists.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="fallBackWarning">Callback to report FallBack to DeviceCode Authentication</param>
        /// <returns></returns>
        public static async Task <IAuthContext> AuthenticateAsync(IAuthContext authContext, bool forceRefresh, CancellationToken cancellationToken, Action fallBackWarning = null)
        {
            // Gets a static instance of IAuthenticationProvider when the client app hasn't changed.
            var authProvider = AuthenticationHelpers.GetAuthProvider(authContext);
            IClientApplicationBase clientApplication = null;

            switch (authContext.AuthProviderType)
            {
            case AuthProviderType.DeviceCodeProvider:
            case AuthProviderType.DeviceCodeProviderFallBack:
                clientApplication = (authProvider as DeviceCodeProvider).ClientApplication;
                break;

            case AuthProviderType.InteractiveAuthenticationProvider:
            {
                var interactiveProvider = (authProvider as InteractiveAuthenticationProvider).ClientApplication;
                //When User is not Interactive, Pre-Emptively Fallback and warn, to DeviceCode
                if (!interactiveProvider.IsUserInteractive())
                {
                    authContext.AuthProviderType = AuthProviderType.DeviceCodeProviderFallBack;
                    fallBackWarning?.Invoke();
                    var fallBackAuthContext = await AuthenticateAsync(authContext, forceRefresh, cancellationToken, fallBackWarning);

                    return(fallBackAuthContext);
                }
                break;
            }

            case AuthProviderType.ClientCredentialProvider:
            {
                clientApplication = (authProvider as ClientCredentialProvider).ClientApplication;
                break;
            }
            }
            try
            {
                // Incremental scope consent without re-instantiating the auth provider. We will use provided instance.
                GraphRequestContext graphRequestContext = new GraphRequestContext();
                graphRequestContext.CancellationToken = cancellationToken;
                graphRequestContext.MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                {
                    {
                        typeof(AuthenticationHandlerOption).ToString(),
                        new AuthenticationHandlerOption
                        {
                            AuthenticationProviderOption = new AuthenticationProviderOption
                            {
                                Scopes       = authContext.Scopes,
                                ForceRefresh = forceRefresh
                            }
                        }
                    }
                };

                // Trigger consent.
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
                httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext);
                await authProvider.AuthenticateRequestAsync(httpRequestMessage);

                IAccount account = null;
                if (clientApplication != null)
                {
                    // Only get accounts when we are using MSAL to get an access token.
                    IEnumerable <IAccount> accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult();
                    account = accounts.FirstOrDefault();
                }

                JwtHelpers.DecodeJWT(httpRequestMessage.Headers.Authorization?.Parameter, account, ref authContext);
                return(authContext);
            }
            catch (AuthenticationException authEx)
            {
                //Interactive Authentication Failure: Could Not Open Browser, fallback to DeviceAuth
                if (IsUnableToOpenWebPageError(authEx))
                {
                    authContext.AuthProviderType = AuthProviderType.DeviceCodeProviderFallBack;
                    //ReAuthenticate using DeviceCode as fallback.
                    var fallBackAuthContext = await AuthenticateAsync(authContext, forceRefresh, cancellationToken);

                    //Indicate that this was a Fallback
                    if (fallBackWarning != null && fallBackAuthContext.AuthProviderType == AuthProviderType.DeviceCodeProviderFallBack)
                    {
                        fallBackWarning();
                    }
                    return(fallBackAuthContext);
                }

                if (authEx.InnerException is TaskCanceledException && cancellationToken.IsCancellationRequested)
                {
                    // Authentication requets timeout.
                    throw new Exception(string.Format(CultureInfo.CurrentCulture, ErrorConstants.Message.DeviceCodeTimeout, Constants.MaxDeviceCodeTimeOut));
                }
                else if (authEx.InnerException is MsalServiceException msalServiceEx &&
                         msalServiceEx.StatusCode == 400 &&
                         msalServiceEx.ErrorCode == "invalid_scope" &&
                         string.IsNullOrWhiteSpace(authContext.TenantId) &&
                         (authContext.AuthProviderType == AuthProviderType.DeviceCodeProvider ||
                          authContext.AuthProviderType == AuthProviderType.DeviceCodeProviderFallBack))
                {
                    // MSAL scope validation error. Ask customer to specify sign-in audience or tenant Id.
                    throw new MsalClientException(msalServiceEx.ErrorCode, $"{msalServiceEx.Message}.\r\n{ErrorConstants.Message.InvalidScope}", msalServiceEx);
                }

                //Something Unknown Went Wrong
                throw authEx.InnerException ?? authEx;
            }
            catch (Exception ex)
            {
                throw ex.InnerException ?? ex;
            }
        }