private void ConfigureSwaggerGen(IServiceCollection services)
        {
            //Use Swashbuckle package to generate a swagger doc that is compliant with OAS3.
            services.AddSwaggerGen(options =>
            {
                //we need to tell swagger to document all enums in camel case, as per the NewtonSoft convention.
                options.DescribeAllParametersInCamelCase();

                var jwtAuthentication = new JwtAuthentication();
                Configuration.Bind(nameof(JwtAuthentication), jwtAuthentication);
                options.AddSecurityDefinition(SwaggerConstants.SecurityDefinitionBearer,
                                              new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        ClientCredentials = new OpenApiOAuthFlow
                        {
                            TokenUrl = new Uri(jwtAuthentication.IdentityProvider + "/connect/token")
                        }
                    },
                    Description = "Client credentials flow"
                });

                //Decorate the swagger doc with the relevant authorization responses, so that SwaggerUi knows to add padlocks and schemes to the relevant endpoints
                options.OperationFilter <AuthorizeOperationFilter>();
                // Set the comments path for the Swagger JSON and UI.
                options.IncludeXmlComments(XmlCommentsFilePath, true);
            })
            //Tell swashbuckle to use whatever other defaults we've established from the NewtonSoft library earlier.
            .AddSwaggerGenNewtonsoftSupport();
        }
Esempio n. 2
0
 public UsersController(IMapper mapper, IConfiguration configuration, IUserRepository userRepository, IUnitOfWork unitofWork)
 {
     this.unitofWork        = unitofWork;
     this.mapper            = mapper;
     this.userRepository    = userRepository;
     this.jwtAuthentication = new JwtAuthentication(configuration);
 }
        public void Setup()
        {
            var client = new MongoClient(Constants.MongoDbConnectionUri());

            _userRepository    = new UsersRepository(client);
            _commentRepository = new CommentsRepository(client);
            _movieRepository   = new MoviesRepository(client);
            _opinionatedUser   = new User
            {
                Name     = "Inigo Montoya",
                Email    = "*****@*****.**",
                Password = "******"
            };
            _anotherUser = new User
            {
                Name     = "Vizzini",
                Email    = "*****@*****.**",
                Password = "******"
            };
            _movieId = "573a1398f29313caabcea974";
            var jwt = new JwtAuthentication
            {
                SecurityKey   = "ouNtF8Xds1jE55/d+iVZ99u0f2U6lQ+AHdiPFwjVW3o=",
                ValidAudience = "https://localhost:5000/",
                ValidIssuer   = "https://localhost:5000/"
            };
            var appSettingsOptions = Options.Create(jwt);

            _userController    = new UserController(_userRepository, _commentRepository, appSettingsOptions);
            _commentController = new CommentController(_commentRepository, _userRepository, appSettingsOptions);
        }
Esempio n. 4
0
            public async Task <Result> Handle(Query request, CancellationToken cancellationToken)
            {
                // Create token handler, which is responsible of generating JWT
                var jwtHandler = new JwtSecurityTokenHandler();
                // Get JWT options from configuration file
                var jwtOptions   = configuration.GetSection(JwtAuthentication.JwtBaseKey);
                var lifetimeDays = int.Parse(jwtOptions["LifetimeDays"]);
                // Token parameters
                var tokenLifetime = TimeSpan.FromDays(lifetimeDays);
                var now           = DateTime.Now;
                // Create token
                var jwt = jwtHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor
                {
                    Audience  = jwtOptions["Audience"],
                    Issuer    = jwtOptions["Issuer"],
                    Expires   = now + tokenLifetime,
                    IssuedAt  = now,
                    NotBefore = now,
                    Subject   = new ClaimsIdentity(new[]
                    {
                        new Claim(nameof(User.Id), request.User.Id.ToString()),
                    }),
                    SigningCredentials =
                        new SigningCredentials(JwtAuthentication.GetSecurityKey(jwtOptions["SecretKey"], jwtOptions["SecurityPhrase"]), SecurityAlgorithms.HmacSha256),
                });

                // Returning created token
                return(await Task.FromResult(new Result
                {
                    Id = request.User.Id,
                    Token = jwtHandler.WriteToken(jwt),
                    ExpiresAt = jwt.ValidTo,
                }));
            }
Esempio n. 5
0
        public SecurityService(IOptions <JwtAuthentication> jwtAuthentication, IStaticConfig staticConfig)
        {
            _jwtAuthentication = jwtAuthentication?.Value ?? throw new ArgumentNullException(nameof(jwtAuthentication));
            _staticConfig      = staticConfig;

            ValidIssuer   = _jwtAuthentication.ValidIssuer;
            ValidAudience = _jwtAuthentication.ValidAudience;
        }
Esempio n. 6
0
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // Authentication service
        JwtAuthentication.AddJwtAuthentication(services);
        services.AddQuartz();                         // <======== THIS LINE
        services.AddSingleton <IHttpRequestScheduler, HttpRequestScheduler>();
    }
Esempio n. 7
0
 public UserController(IOptions <JwtAuthentication> jwtAuthentication,
                       UserManager <User> userManager,
                       SignInManager <User> signInManager,
                       IMapper mapper)
 {
     _jwtAuthentication = jwtAuthentication.Value;
     _signInManager     = signInManager;
     _mapper            = mapper;
     _userManager       = userManager;
 }
Esempio n. 8
0
 public static Matrimony.Model.Base.Response CreateResponse(JwtAuthentication jwtAuthentication, HttpRequest httpRequest, Matrimony.Model.Base.Response response)
 {
     if (response != null)
     {
         var token = new AuthenticationHelper().VerifyToken(jwtAuthentication, httpRequest);
         response.Metadata.Token = token;
         return(response);
     }
     return(null);
 }
Esempio n. 9
0
 /// <summary>Initializes a new instance of the <see cref="AuthController" /> class.</summary>
 /// <param name="logger">The logger.</param>
 /// <param name="jwtAuthentication">The JWT authentication.</param>
 /// <param name="accountService">The account service.</param>
 /// <param name="staticConfig">The static configuration.</param>
 /// <param name="securityService">The security service.</param>
 /// <exception cref="ArgumentNullException">jwtAuthentication</exception>
 public AuthController(ILogger <AuthController> logger,
                       IOptions <JwtAuthentication> jwtAuthentication,
                       IAccountService accountService,
                       IStaticConfig staticConfig,
                       ISecurityService securityService)
 {
     _logger            = logger;
     _jwtAuthentication = jwtAuthentication?.Value ?? throw new ArgumentNullException(nameof(jwtAuthentication));
     _accountService    = accountService;
     _staticConfig      = staticConfig;
     _securityService   = securityService;
 }
Esempio n. 10
0
 public AccountApiController(UserManager <ApplicationUser> userManager,
                             SignInManager <ApplicationUser> signInManager,
                             ILogger <AccountController> logger,
                             RoleManager <IdentityRole> roleManager, JwtAuthentication JwtAuthentication, IStoreManager storeManager)
 {
     _userManager       = userManager;
     _signInManager     = signInManager;
     _logger            = logger;
     _roleManager       = roleManager;
     _JwtAuthentication = JwtAuthentication;
     _storeManager      = storeManager;
 }
        public LoginController(IUserServices user, JwtAuthentication jwt)
        {
            _repository = user;
            _jwt        = jwt;


            MapperConfiguration cofiguration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <UserViewModel, UserDto>().ReverseMap();
            });

            _mapper = cofiguration.CreateMapper();
        }
Esempio n. 12
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpStatusCode statusCode;
            string         token;

            //determine whether a jwt exists or not
            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
                return(base.SendAsync(request, cancellationToken));
            }
            try
            {
                SecurityToken             securityToken;
                JwtSecurityTokenHandler   handler = new JwtSecurityTokenHandler();
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience    = "http://abc.com", //audienceConfig["Aud"],
                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer    = "http://abc.com", //audienceConfig["Iss"],
                    // Validate the token expiry
                    ValidateLifetime  = true,
                    ClockSkew         = TimeSpan.Zero,
                    LifetimeValidator = this.LifetimeValidator,
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    // IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(Secret)),
                    IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(Secret)),
                };
                //extract and assign the user of the jwt

                //Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
                string username = "******";
                Thread.CurrentPrincipal  = JwtAuthentication.ValidateToken(token, out username);;
                HttpContext.Current.User = Thread.CurrentPrincipal;
                return(base.SendAsync(request, cancellationToken));
            }
            catch (SecurityTokenValidationException ex)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (Exception)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }
            return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode) { }));
        }
Esempio n. 13
0
 public ManageStoreApiController(UserManager <ApplicationUser> userManager,
                                 SignInManager <ApplicationUser> signInManager,
                                 ILogger <AccountController> logger, IUserManager manager, IHostingEnvironment env,
                                 RoleManager <IdentityRole> roleManager, JwtAuthentication JwtAuthentication, IStoreManager storeManager)
 {
     _userManager       = userManager;
     _signInManager     = signInManager;
     _logger            = logger;
     _roleManager       = roleManager;
     _JwtAuthentication = JwtAuthentication;
     _manager           = manager;
     _storeManager      = storeManager;
     _env = env;
 }
Esempio n. 14
0
        public async Task TestLogsInUser()
        {
            var jwt = new JwtAuthentication
            {
                SecurityKey   = "ouNtF8Xds1jE55/d+iVZ99u0f2U6lQ+AHdiPFwjVW3o=",
                ValidAudience = "https://*****:*****@mongodb.com",
                Password  = "******",
                AuthToken = jwt.SecurityKey
            };

            try
            {
                var result = await _userRepository.LoginUserAsync(user);

                Assert.IsNotNull(result.ErrorMessage);
                Assert.AreEqual("No user found. Please check the email address.",
                                result.ErrorMessage);

                var addUserResult = await _userRepository.AddUserAsync(user.Name,
                                                                       user.Email, user.Password);

                Assert.IsNotNull(addUserResult.User);

                result = await _userRepository.LoginUserAsync(user);

                Assert.IsNotNull(result.User);
                Assert.AreEqual("Test User 2", result.User.Name);
                Assert.AreEqual("ouNtF8Xds1jE55/d+iVZ99u0f2U6lQ+AHdiPFwjVW3o=",
                                result.User.AuthToken);
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }
            finally
            {
                //cleanup
                await _userRepository.LogoutUserAsync(user.Email);

                await _userRepository.DeleteUserAsync(user.Email);
            }
        }
        public static async Task <IActionResult> GetExpenses(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = BaseRoute)]
            HttpRequestMessage req,
            [Table("expenses", Connection = StorageConnectionName)]
            CloudTable expenseTable,
            ILogger log)
        {
            var claimsPrincipal = await JwtAuthentication.ValidateTokenAsync(req.Headers.Authorization);

            var query = new TableQuery <ExpenseTableEntity>().Where(
                TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, TemporaryPartitionKey)
                );
            var segment = await expenseTable.ExecuteQuerySegmentedAsync(query, null);

            return(new OkObjectResult(segment.Results.Select(ExpenseMappings.ToExpense)));
        }
Esempio n. 16
0
        public void Setup()
        {
            var client = new MongoClient(Constants.MongoDbConnectionUri());

            _userRepository     = new UsersRepository(client);
            _commentsRepository = new CommentsRepository(client);
            var jwt = new JwtAuthentication
            {
                SecurityKey   = "ouNtF8Xds1jE55/d+iVZ99u0f2U6lQ+AHdiPFwjVW3o=",
                ValidAudience = "https://localhost:5000/",
                ValidIssuer   = "https://localhost:5000/"
            };

            var appSettingsOptions = Options.Create(jwt);

            _userController = new UserController(_userRepository, _commentsRepository, appSettingsOptions);
        }
Esempio n. 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var logger = Logger.CreateLogger <Startup>();

            // Identifies the environment upon system start
            if (HostingEvironment.IsDevelopment())
            {
                logger.LogInformation("Start Niente application in development environment");
            }
            else
            {
                logger.LogInformation("Start Niente application in production environment");
            }

            // Add CORS policy
            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy",
                                  new CorsPolicyBuilder()
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowAnyOrigin()
                                  .AllowCredentials()
                                  .Build());
            });

            // Register database
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            Identity.Configure(services);

            JwtAuthentication.Configure(services, Configuration);

            // Register custom username / password combination validator
            services.AddTransient <IPasswordValidator <ApplicationUser>, PwConstraintValidator>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("SiteCorsPolicy"));
            });
        }
Esempio n. 18
0
        public void AccessPoliciesLifeCycleTest()
        {
            using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
            {
                try
                {
                    CreateVideoAnalyzerAccount();

                    var accessPoliies = VideoAnalyzerClient.AccessPolicies.List(ResourceGroup, AccountName);
                    Assert.Empty(accessPoliies);

                    var accessPolicyName = TestUtilities.GenerateName("ap");

                    var a = new JwtAuthentication()
                    {
                        Audiences = new List <string>()
                        {
                            "testAudience"
                        }
                    };
                    var aa = a.Audiences;

                    VideoAnalyzerClient.AccessPolicies.CreateOrUpdate(ResourceGroup, AccountName, accessPolicyName, AccessPolicyRole.Reader,
                                                                      new JwtAuthentication()
                    {
                        Audiences = new List <string>()
                        {
                            "testAudience"
                        },
                        Issuers = new List <string>()
                        {
                            "testIssuers"
                        },
                        Keys = new List <TokenKey>()
                        {
                            new RsaTokenKey
                            {
                                Alg = AccessPolicyRsaAlgo.RS256,
                                Kid = "123",
                                N   = "YmFzZTY0IQ==",
                                E   = "ZLFzZTY0IQ=="
                            }
                        }
                    });

                    var accessPolicy = VideoAnalyzerClient.AccessPolicies.Get(ResourceGroup, AccountName, accessPolicyName);
                    Assert.NotNull(accessPolicy);
                    Assert.Equal(accessPolicyName, accessPolicy.Name);

                    accessPoliies = VideoAnalyzerClient.AccessPolicies.List(ResourceGroup, AccountName);
                    Assert.NotNull(accessPoliies);
                    Assert.Single(accessPoliies);

                    VideoAnalyzerClient.AccessPolicies.Delete(ResourceGroup, AccountName, accessPolicyName);

                    accessPoliies = VideoAnalyzerClient.AccessPolicies.List(ResourceGroup, AccountName);
                    Assert.Empty(accessPoliies);
                }
                finally
                {
                    DeleteVideoAnalyzerAccount();
                }
            }
        }
Esempio n. 19
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(IJwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);

                this.httpServer = new HttpServer();
                //this.httpServer = new HttpServer(new LogSniffer());

                StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));

                string Root = File.Path;
                Root = Root.Substring(0, Root.Length - 11);
                this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));

                this.httpServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException("/Index.md");
                });

                this.httpServer.Register("/Momentary", (req, resp) =>
                {
                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");

                    if (req.Header.Accept != null)
                    {
                        switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

                        case "application/json":
                            this.ReturnMomentaryAsJson(req, resp);
                            break;

                        default:
                            throw new NotAcceptableException();
                        }
                    }
                    else
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }

                    return(Task.CompletedTask);
                }, this.tokenAuthentication);

                this.httpServer.Register("/Set", null, async(req, resp) =>
                {
                    try
                    {
                        if (!req.HasData)
                        {
                            throw new BadRequestException();
                        }

                        if (!(req.DecodeData() is string s) || !CommonTypes.TryParse(s, out bool OutputValue))
                        {
                            throw new BadRequestException();
                        }

                        if (req.Header.Accept != null)
                        {
                            switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                            {
                            case "text/xml":
                            case "application/xml":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsXml(req, resp);
                                break;

                            case "application/json":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsJson(req, resp);
                                break;

                            default:
                                throw new NotAcceptableException();
                            }
                        }
                        else
                        {
                            await this.SetOutput(OutputValue, req.RemoteEndPoint);
                            this.ReturnMomentaryAsXml(req, resp);
                        }

                        await resp.SendResponse();
                    }
                    catch (Exception ex)
                    {
                        await resp.SendResponse(ex);
                    }
                }, false, this.tokenAuthentication);

                this.httpServer.Register("/Login", null, (req, resp) =>
                {
                    if (!req.HasData || req.Session is null)
                    {
                        throw new BadRequestException();
                    }

                    object Obj = req.DecodeData();

                    if (!(Obj is Dictionary <string, string> Form) ||
                        !Form.TryGetValue("UserName", out string UserName) ||
                        !Form.TryGetValue("Password", out string Password))
                    {
                        throw new BadRequestException();
                    }

                    string From = null;

                    if (req.Session.TryGetVariable("from", out Variable v))
                    {
                        From = v.ValueObject as string;
                    }

                    if (string.IsNullOrEmpty(From))
                    {
                        From = "/Index.md";
                    }

                    IUser User = this.Login(UserName, Password);
                    if (User != null)
                    {
                        Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);

                        req.Session["User"] = User;
                        req.Session.Remove("LoginError");

                        throw new SeeOtherException(From);
                    }
                    else
                    {
                        Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
                        req.Session["LoginError"] = "Invalid login credentials provided.";
                    }

                    throw new SeeOtherException(req.Header.Referer.Value);
                }, true, false, true);

                this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
                {
                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        !(v.ValueObject is IUser User))
                    {
                        throw new ForbiddenException();
                    }

                    string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName));

                    resp.ContentType = JwtCodec.ContentType;
                    resp.Write(Token);

                    return(Task.CompletedTask);
                }, true, false, true);
            }
Esempio n. 20
0
 public ConfigureJwtBearerOptions(JwtAuthentication jwtAuthentication)
 {
     _jwtAuthentication = jwtAuthentication ?? throw new System.ArgumentNullException(nameof(jwtAuthentication));
 }
 public AuthController(JwtAuthentication jwtAuthentication, IUserRepository userRepository)
 {
     this.userRepository    = userRepository;
     this.jwtAuthentication = jwtAuthentication; //gfdgfdg blbblblblblbl
 }
Esempio n. 22
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");
                instance = this;

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(JwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(Graph).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                             // Relay.
                        this.arduino.digitalWrite(9, 0);                                     // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                          // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            this.lastMotion = (value == PinState.HIGH);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);

                this.httpServer = new HttpServer();
                //this.httpServer = new HttpServer(new LogSniffer());

                StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));

                string Root = File.Path;
                Root = Root.Substring(0, Root.Length - 11);
                this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));

                this.httpServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException("/Index.md");
                });

                this.httpServer.Register("/Momentary", (req, resp) =>
                {
                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");

                    if (req.Header.Accept != null)
                    {
                        switch (req.Header.Accept.GetBestContentType("text/xml", "application/xml", "application/json", "image/png", "image/jpeg", "image/webp"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

                        case "application/json":
                            this.ReturnMomentaryAsJson(req, resp);
                            break;

                        case "image/png":
                            this.ReturnMomentaryAsPng(req, resp);
                            break;

                        case "image/jpg":
                            this.ReturnMomentaryAsJpg(req, resp);
                            break;

                        case "image/webp":
                            this.ReturnMomentaryAsWebp(req, resp);
                            break;

                        default:
                            throw new NotAcceptableException();
                        }
                    }
                    else
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }
                }, this.tokenAuthentication);

                this.httpServer.Register("/MomentaryPng", (req, resp) =>
                {
                    IUser User;

                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        (User = v.ValueObject as IUser) is null)
                    {
                        throw new ForbiddenException();
                    }

                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
                    this.ReturnMomentaryAsPng(req, resp);
                }, true, false, true);

                this.httpServer.Register("/Login", null, (req, resp) =>
                {
                    if (!req.HasData || req.Session is null)
                    {
                        throw new BadRequestException();
                    }

                    object Obj = req.DecodeData();

                    if (!(Obj is Dictionary <string, string> Form) ||
                        !Form.TryGetValue("UserName", out string UserName) ||
                        !Form.TryGetValue("Password", out string Password))
                    {
                        throw new BadRequestException();
                    }

                    string From = null;

                    if (req.Session.TryGetVariable("from", out Variable v))
                    {
                        From = v.ValueObject as string;
                    }

                    if (string.IsNullOrEmpty(From))
                    {
                        From = "/Index.md";
                    }

                    IUser User = this.Login(UserName, Password);
                    if (User != null)
                    {
                        Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);

                        req.Session["User"] = User;
                        req.Session.Remove("LoginError");

                        throw new SeeOtherException(From);
                    }
                    else
                    {
                        Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
                        req.Session["LoginError"] = "Invalid login credentials provided.";
                    }

                    throw new SeeOtherException(req.Header.Referer.Value);
                }, true, false, true);

                this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
                {
                    IUser User;

                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        (User = v.ValueObject as IUser) is null)
                    {
                        throw new ForbiddenException();
                    }

                    string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName));

                    resp.ContentType = JwtCodec.ContentType;
                    resp.Write(Token);
                }, true, false, true);
            }
Esempio n. 23
0
 public AccountController(ILogger <AccountController> logger, TuExamContext context, IOptions <JwtAuthentication> jwt)
 {
     this._logger  = logger;
     this._context = context;
     this._jwt     = jwt.Value;
 }
Esempio n. 24
0
 public AccountApiController(IAccountManager accountManager, JwtAuthentication _JwtAuthentication)
 {
     _accountManager   = accountManager;
     JwtAuthentication = _JwtAuthentication;
 }
Esempio n. 25
0
 public JwtSecurityTokenHelper(IOptionsMonitor <JwtAuthentication> options)
 {
     _jwtAuthentication = options.CurrentValue;
 }
Esempio n. 26
0
 public TokenProvider(JwtAuthentication jwtAuthentication)
 {
     _jwtAuthentication = jwtAuthentication;
 }