Example #1
0
        public void GenerateEncodedToken_Should_Generate_Proper_Token_With_Extra_Claims(string userId, string email, Fixture claimsFixture)
        {
            // Arrange
            // To enable AutoFixture to generate claims
            claimsFixture.Behaviors.Add(new OmitOnRecursionBehavior());
            claimsFixture.Customize <Claim>(
                c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));

            var claims = claimsFixture.Create <List <Claim> >();

            // Act
            var result = _jwtFactory.GenerateEncodedToken(userId, email, claims);

            // Assert
            var jwt = new JwtSecurityToken(result);

            jwt.Claims.ShouldContain(c => c.Type == JwtRegisteredClaimNames.Iss && c.Value == _jwtConfiguration.Issuer);
            jwt.Claims.ShouldContain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId);
            jwt.Claims.ShouldContain(c => c.Type == JwtRegisteredClaimNames.Email && c.Value == email);
            jwt.Claims.ShouldContain(c => c.Type == JwtRegisteredClaimNames.Aud && c.Value == _jwtConfiguration.Audience);

            // The jwt should contain all of the extra claims
            claims.ShouldAllBe(c => jwt.Claims.Any(x => x.Type == c.Type && x.Value == c.Value));

            jwt.ValidFrom.ShouldBe(DateTime.UtcNow, TimeSpan.FromSeconds(10));
            jwt.ValidTo.ShouldBe(DateTime.UtcNow.Add(_jwtConfiguration.ValidFor), TimeSpan.FromSeconds(10));
        }
Example #2
0
        public async Task <Option <JwtModel, Error> > Login(LoginUserModel model)
        {
            var loginResult = await(await UserManager.FindByEmailAsync(model.Email))
                              .SomeNotNull()
                              .FilterAsync(async user => await UserManager.CheckPasswordAsync(user, model.Password));



            return(loginResult.Match(
                       user =>
            {
                Company company = _companyService.GetCompany(user.Email.Split('@')[1]);

                return new JwtModel
                {
                    TokenString = JwtFactory.GenerateEncodedToken(user.Id, user.Email, new List <Claim>
                    {
                        new Claim("CompanyGuid", company.Guid.ToString()),
                        new Claim("CompanyName", company.Name),
                        new Claim("CompanyDomain", company.DomainName)
                    })
                }.Some <JwtModel, Error>();
            },
                       () => Option.None <JwtModel, Error>(new Error("Invalid credentials."))));
        }
Example #3
0
        public async void GenerateEncodedToken_GivenValidInputs_ReturnsExpectedTokenData()
        {
            // arrange
            var token            = Guid.NewGuid().ToString();
            var id               = Guid.NewGuid().ToString();
            var key              = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("secret_key"));
            var jwtIssuerOptions = new JwtIssuerOptions
            {
                Issuer             = "",
                Audience           = "",
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };

            var mockJwtTokenHandler = new Mock <IJwtTokenHandler>();

            mockJwtTokenHandler.Setup(handler => handler.WriteToken(It.IsAny <JwtSecurityToken>())).Returns(token);

            var jwtFactory = new JwtFactory(mockJwtTokenHandler.Object, Options.Create(jwtIssuerOptions));

            // act
            var result = await jwtFactory.GenerateEncodedToken(id, "userName");

            // assert
            Assert.Equal(token, result.Token);
        }
        public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!userService.IsAuthorized(credentials.UserName, credentials.Password))
            {
                return(BadRequest("login failed"));
            }

            // Serialize and return the response
            try
            {
                var response = new
                {
                    access_token = jwtFactory.GenerateEncodedToken(credentials.UserName)
                };

                var json = JsonConvert.SerializeObject(response, new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented
                });
                return(Ok(json));
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.GetBaseException().Message);
                throw;
            }
        }
Example #5
0
        public static async Task <string> GenerateJwt(ClaimsIdentity identity, JwtFactory jwtFactory, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings)
        {
            var response = new
            {
                id         = identity.Claims.Single(c => c.Type == "id").Value,
                auth_token = await jwtFactory.GenerateEncodedToken(userName, identity),
                expires_in = (int)jwtOptions.ValidFor.TotalSeconds
            };

            return(JsonConvert.SerializeObject(response, serializerSettings));
        }
Example #6
0
        public async Task <IActionResult> Post([FromBody] LoginModel loginModel)
        {
            var login = await CheckPasswordAsync(loginModel.Email, loginModel.Password);

            if (!login)
            {
                return(BadRequest());
            }

            return(new OkObjectResult(new
            {
                token = jwtFactory.GenerateEncodedToken(loginModel.Email)
            }));
        }
Example #7
0
        public async Task WhenGeneratingEncodedTokenItShouldReturnAnAuthToken()
        {
            _jwtOptionsnMock.Setup(p => p.Value)
            .Returns(new JwtOptions {
                Audience = "", Issuer = "", SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256), Subject = "ASubject", ValidFor = new TimeSpan(0, 0, 7200)
            });

            _objectToTest = new JwtFactory(_jwtOptionsnMock.Object);
            var claims = _objectToTest.GenerateClaimsIdentity("UserName", "Id");

            var token = await _objectToTest.GenerateEncodedToken("UserName", claims);

            Assert.NotNull(token);
        }
Example #8
0
        public async Task <Option <JwtModel, Error> > Login(LoginUserModel model)
        {
            var loginResult = await(await UserManager.FindByEmailAsync(model.Email))
                              .SomeNotNull()
                              .FilterAsync(async user => await UserManager.CheckPasswordAsync(user, model.Password));

            return(loginResult.Match(
                       user =>
            {
                return new JwtModel
                {
                    TokenString = JwtFactory.GenerateEncodedToken(user.Id, user.Email, new List <Claim>())
                }.Some <JwtModel, Error>();
            },
                       () => Option.None <JwtModel, Error>(new Error("Invalid credentials."))));
        }
        public async Task <Option <JwtModel, Error> > Login(LoginUserModel model)
        {
            var loginResult = await(await UserManager.FindByEmailAsync(model.Email))
                              .SomeNotNull(new Error("Such an user does not exist!"))
                              .FilterAsync(
                async user => await UserManager.CheckPasswordAsync(user, model.Password),
                new Error("Invalid credentials."));

            return(await loginResult.FlatMapAsync(async user =>
            {
                var claims = await UserManager.GetClaimsAsync(user);
                return new JwtModel(
                    JwtFactory.GenerateEncodedToken(
                        userId: user.Id,
                        email: user.Email,
                        additionalClaims: claims)).Some <JwtModel, Error>();
            }));
        }
 private string GenerateToken(string userId, string email) =>
 JwtFactory.GenerateEncodedToken(userId, email, new List <Claim>());
Example #11
0
        public async Task <string> GenerateJwt(JwtFactory jwtFactory, AppUser user, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings, List <string> roles)
        {
            var response = await jwtFactory.GenerateEncodedToken(user, roles);

            return(response);
        }
Example #12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, ILogger logger, IHostApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
            }
            else
            {
                app.ConfigureExceptionHandler(logger);
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader());
            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseSerilogRequestLogging();

            app.UseAuthentication();
            app.UseRouting();

            app.Use(async(context, next) =>
            {
                // Do work that doesn't write to the Response.
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });


            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            // Check for lifetime shutdown working with WebSocket active
            lifetime.ApplicationStopping.Register(() =>
            {
                logger.Information("Wikibot is shutting down.");
            }, true);

            lifetime.ApplicationStopped.Register(() =>
            {
                logger.Information("Wikibot has stopped.");
            }, true);

            var configuration = app.ApplicationServices.GetRequiredService <IConfiguration>();
            var dashboardUrl  = configuration["DashboardURL"];

            app.Use(async(context, next) =>
            {
                var url = context.Request.Path.Value;

                // Redirect to an external URL
                if (url.Contains("/Dashboard") && (context.User.IsInRole("WikiMod") || context.User.IsInRole("BotAdmin")))
                {
                    var jwtOptions = app.ApplicationServices.GetRequiredService <IOptions <JwtIssuerOptions> >();
                    var factory    = new JwtFactory(jwtOptions);
                    var jwtToken   = await factory.GenerateEncodedToken(context.User.Identity.Name, context.User.Identities.First());
                    context.Response.Redirect($"{dashboardUrl}?auth_token= {jwtToken}"); //Update URL
                    return;                                                              // short circuit
                }

                await next();
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            CreateUserRoles(serviceProvider, configuration).Wait();
        }