예제 #1
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var authResult = await _refitAuth.ObterTokenAsync(model);

            if (authResult.IsSuccessStatusCode)
            {
                var authResponse = await authResult.Content.ReadAsStringAsync();

                var tokenModel = JsonConvert.DeserializeObject <TokenModel>(authResponse);

                if (!JwtTokenValidator.ValidaToken(tokenModel.Token))
                {
                    ModelState.AddModelError("", "Login inválido!");
                    return(View(model));
                }

                Response.Cookies.Append("token", tokenModel.Token);

                return(RedirectToAction("Index", "Home"));
            }

            ModelState.AddModelError("", "Login inválido!");
            return(View(model));
        }
예제 #2
0
        public void ValidateAllTokens(JwtTokenValidator validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException(nameof(validator));
            }

            validator.ValidateAllTokens(notif[tokens].Values <string>());
        }
예제 #3
0
        public ActionResult Details(string authToken)
        {
            TokenData tokenData = new TokenData();

            if (JwtTokenValidator.Validate(authAudience, authToken, ref tokenData))
            {
                return(View(tokenData));
            }
            else
            {
                return(View("Error"));
            }
        }
예제 #4
0
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var token     = filterContext.RequestContext.HttpContext.Request.QueryString.Get("authToken");
            var tokenData = new TokenData();

            if (!JwtTokenValidator.Validate(ConfigurationManager.AppSettings["ADAppClientId"], token, ref tokenData))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "401"
                };
            }
        }
        static void Main(string[] args)
        {
            const string queueSasKey = "https://testfunctionsfo97a4.queue.core.windows.net/notifqueue?st=2019-09-05T23%3A00%3A14Z&se=2019-10-06T20%3A00%3A00Z&sp=rup&sv=2018-03-28&sig=VgevMRmMB0miZbIQzpOgteyrIlLbwGKfsO48dJ%2F2WtQ%3D";
            const string blobSasKey  = "https://testfunctionsfo97a4.blob.core.windows.net/notificationblobs?st=2019-08-06T22%3A40%3A12Z&se=2019-09-07T18%3A40%3A00Z&sp=rl&sv=2018-03-28&sr=c&sig=kz5ah8ziqBKn6oyX1FoNihfCSM1fVAc1qvvzwsvjA4c%3D";

            var authProvider          = AuthSettings.isUserAuthentication ? (MyAuthenticationProvider) new UserAuthenticationProvider() : (MyAuthenticationProvider) new AppOnlyAuthenticationProvider();
            GraphServiceClient client = GetAuthenticatedClient(authProvider);
            var token = authProvider.GetAccessTokenAsync().Result;

            var subManager = new SubscriptionManager(client, NotificationProcessingSettings.notificationUrl, NotificationProcessingSettings.lifecycleNotificationUrl);

            //var subs = subManager.GetAllSubscriptionsAsync().Result;
            subManager.DeleteAllSubscriptionsAsync().Wait();

            //var createdSub = subManager.CreateSubscriptionAsync("/users", "updated", "bobState").Result;
            var createdSub = subManager.CreateSubscriptionAsync("/teams/allMessages", "created,updated", TimeSpan.FromMinutes(58), "bobState", DummyKeyStore.GetPublicKeyLocal(NotificationProcessingSettings.encryptionCertificateId), NotificationProcessingSettings.encryptionCertificateId, true).Result;

            var messenger     = new MessageManager(microsoftGraphCanary, "95432da5-e897-4fd4-8141-3df339ca1141", "19:[email protected]");
            var ct            = new CancellationToken();
            var messengerTask = messenger.StartAsync(ct);

            Console.WriteLine("Subscription created. Waiting for notifications.");
            var notifications = NotificationDownloader.LoopOverNotificationsFromQueue(queueSasKey, messengerTask);

            //var notifications = NotificationDownloader.GetNotificationsFromBlobs(blobSasKey, DateTime.Parse("2019-08-04"));

            var audiences = new[] { AuthSettings.applicationId };
            var validator = new JwtTokenValidator(audiences);

            validator.InitializeOpenIdConnectConfigurationAsync().Wait();

            foreach (var notifContent in notifications)
            {
                var p = new NotificationProcessor(notifContent);
                p.ValidateAllTokens(validator);

                // renew any subscriptions that require re-authorization
                foreach (var subId in p.GetSubscriptionsToReauthorize())
                {
                    subManager.RenewSubscriptionAsync(subId, TimeSpan.FromMinutes(58)).Wait();
                }

                var results = p.DecryptAllNotifications().ToArray();
                // print portions of the content to console, just for fun
                foreach (var notif in results)
                {
                    PrintContentToConsole(notif);
                }
            }
            return;
        }
예제 #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();

            services.AddDbContext <UserDbContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <Server.DAL.Models.User, Role>()
            .AddEntityFrameworkStores <UserDbContext>()
            .AddDefaultTokenProviders();


            // Auto Mapper Configurations
            var mappingConfig = new MapperConfiguration(
                mc =>
            {
                mc.AddProfile(new UserManagementMappingProfile());
            });

            var mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                var validator = new JwtTokenValidator();
                x.SecurityTokenValidators.Add(validator);
            });

            services.AddAuthorization();
        }
        public void JwtToken_Should_Be_Validated()
        {
            var response = _openIdClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address      = "/connect/token",
                ClientId     = "client",
                ClientSecret = "secret",
                Scope        = "api1"
            }).Result;

            string token     = response.AccessToken;
            var    validator = new JwtTokenValidator(Options.Create <JwtTokenOptions>(new JwtTokenOptions()
            {
                Authority = "https://server"
            }), _openIdClient);
            var p = validator.Validate(token).Result;

            Assert.NotNull(p.FindFirst("iss"));
        }
예제 #8
0
        public override async Task <AuthResponse> Auth(AuthRequest request, ServerCallContext context)
        {
            var user = await _ctx.Users.FirstOrDefaultAsync(t =>
                                                            t.Login == request.Login && t.Password == request.Password);

            if (user == null)
            {
                return(new AuthResponse
                {
                    Status = ResponseStatus.RsError,
                    ResponseDescription = "Имя пользователя или пароль введены не верно."
                });
            }

            var token = JwtTokenValidator.GetToken(user.Login, user.Role.ToString());

            return(new AuthResponse
            {
                Token = token,
                Status = ResponseStatus.RsOk
            });
        }
예제 #9
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (!SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()))
                {
                    _log.DebugFormat("Single sign-on settings are disabled");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsDisabled), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                var settings = SettingsManager.Instance.LoadSettings <SsoSettings>(TenantProvider.CurrentTenantID);
                if (!settings.EnableSso)
                {
                    _log.DebugFormat("Single sign-on is disabled");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsDisabled), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                if (context.User.Identity.IsAuthenticated)
                {
                    _log.DebugFormat("User {0} already authenticated");
                    context.Response.Redirect(CommonLinkUtility.GetDefault(), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (context.Request["auth"] == "true")
                {
                    context.Response.Redirect(settings.SsoEndPoint, false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                UserInfo userInfo;

                if (settings.TokenType != TokenTypes.JWT)
                {
                    _log.Error("Settings TokenType  is not JWT");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsEnexpectedTokenType), true);
                    return;
                }
                var jwtEncodedString = context.Request.QueryString[JWT];
                if (string.IsNullOrWhiteSpace(jwtEncodedString))
                {
                    _log.Error("JWT token is null or empty");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsEmptyToken), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                _log.Debug("Trying to authenticate using JWT");
                var tokenValidator = new JwtTokenValidator();

                var audience = context.Request.Url.AbsoluteUri.
                               Replace(context.Request.Url.AbsolutePath, string.Empty).Replace(context.Request.Url.Query, string.Empty);
                tokenValidator.ValidateJsonWebToken(jwtEncodedString, settings, new List <string> {
                    audience, audience + "/"
                });

                if (tokenValidator.ClaimsPrincipalReceived == null ||
                    !tokenValidator.ClaimsPrincipalReceived.Identity.IsAuthenticated ||
                    !tokenValidator.CheckJti() ||
                    !tokenValidator.IsValidEmail(tokenValidator.ClaimsPrincipalReceived))
                {
                    _log.Error("JWT token is not valid");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsNotValidToken), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                var jwtUserCreator = new JwtUserCreator();
                userInfo = jwtUserCreator.CreateUserInfo(tokenValidator.ClaimsPrincipalReceived, settings.Issuer);
                if (userInfo == Constants.LostUser)
                {
                    _log.Error("Can't create userInfo using current JWT token");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsCantCreateUser), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                if (userInfo.Status == EmployeeStatus.Terminated)
                {
                    _log.Error("Current user is terminated");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsUserTerminated), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                AddUser(tokenValidator.ClaimsPrincipalReceived, userInfo);
                MessageService.Send(context.Request, MessageAction.LoginSuccessViaSSO);
                context.Response.Redirect(CommonLinkUtility.GetDefault(), false);
                context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception e)
            {
                _log.ErrorFormat("Unexpected error. {0}", e);
                context.Response.Redirect(AUTH_PAGE, false);
                context.ApplicationInstance.CompleteRequest();
            }
        }
예제 #10
0
        private ClaimsPrincipal Verify(string token)
        {
            var validator = new JwtTokenValidator();

            return(validator.Verify(token));
        }
예제 #11
0
 public void ClassLevelSetUp()
 {
     _tokenManager      = new Mock <ITokenManager>();
     _jwtTokenValidator = new JwtTokenValidator(_tokenManager.Object);
     _jwtTokenValidator.Should().BeOfType(typeof(JwtTokenValidator));
 }