/// <summary> /// Will request authentication. /// </summary> /// <remarks> /// Sends respond to client, nothing else can be done with the response after this. /// </remarks> /// <param name="mod"></param> /// <param name="request"></param> /// <param name="response"></param> protected virtual void RequestAuthentication(AuthenticationModule mod, IHttpRequest request, IHttpResponse response) { string theResponse = mod.CreateResponse(GetRealm(request)); response.AddHeader("www-authenticate", theResponse); response.Reason = "Authentication required."; response.Status = HttpStatusCode.Unauthorized; }
public void Load_ValidConfiguration() { var module = new AuthenticationModule(); var config = Make_AuthenticationSettings(); PortalApplication.Setup(m => m.GetSettings<AuthenticationSettings>("Authentication")).Returns(Make_AuthenticationSettings()); module.Load(PortalApplication.Object); }
protected JWTAuthenticationIdentity GetJWTIdentity() { if (User?.Identity == null) { return(null); } return(AuthenticationModule.PopulateUser(User.Identity as ClaimsIdentity)); }
#pragma warning disable 1591 public AccountController( #pragma warning restore 1591 AuthenticationModule authenticationModule, AuthorizationModule authorizationModule, IEventLogger apiEventLogger) { this.authenticationModule = authenticationModule; this.authorizationModule = authorizationModule; this.apiEventLogger = apiEventLogger; }
public override void OnAuthorization(AuthorizationContext filterContext) { if (SkipAuthorization(filterContext.ActionDescriptor)) { return; } AuthenticationModule module = new AuthenticationModule(); module.Authenticate(); }
public void GetFormsAuthenticationTicket_WithRequestHavingNoCookies_ReturnsNull() { // arrange var module = new AuthenticationModule(); // act var authTicket = module.GetFormsAuthenticationTicket(null); // assert Assert.IsNull(authTicket); }
#pragma warning disable 1591 public SubscriptionController( #pragma warning restore 1591 AuthenticationModule authenticationModule, AuthorizationModule authorizationModule, SubscriptionManager subscriptionManager, IEventLogger apiEventLogger) { this.authenticationModule = authenticationModule; this.authorizationModule = authorizationModule; this.subscriptionManager = subscriptionManager; this.apiEventLogger = apiEventLogger; }
protected void btnLogout_Click(object sender, System.EventArgs e) { // Log out AuthenticationModule am = (AuthenticationModule)Context.ApplicationInstance.Modules["AuthenticationModule"]; am.Logout(); this.pnlLogin.Visible = true; this.pnlUserInfo.Visible = false; // Redirect to self to refresh rendering of the page because this event happens after // everything is already constructed. Context.Response.Redirect(Context.Request.RawUrl); }
protected void BtnCommand_Click(object sender, EventArgs e) { string retUrl = ""; try { AuthenticationModule am = new AuthenticationModule(); if (am != null) { int result = am.AuthenticateUser(txtUsername.Text, txtPassword.Text, chkrememberme.Checked); if (result > 0) { if (Request.Params["ru"] != null) { retUrl = Request.QueryString["ru"]; Response.Redirect(Util.BaseSiteUrl + "a.aspx?p=" + retUrl, true); } else { Response.Redirect(Util.BaseSiteUrl + "a.aspx?p=admin-home", true); } } else if (result < 0) { this.lblError.Text = "You have not activated you account, Kindly check your email and click on the activate this account link."; this.lblError.Visible = true; ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1; if (System.Convert.ToInt32(ViewState["Tries"]) > 3) { Response.Redirect("~/Denied.aspx?times=" + ViewState["Tries"].ToString(), true); } } else { this.lblError.Text = "Invalid user name or password."; this.lblError.Visible = true; // Otherwise, increment number of tries. ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1; if (System.Convert.ToInt32(ViewState["Tries"]) > 3) { Response.Redirect("Denied.aspx?times=" + ViewState["Tries"].ToString(), true); } } } else { throw new Exception("Modules Not Supported on the Server"); } } catch (Exception ex) { this.lblError.Text = ex.Message; } }
public void AuthenticateRequest_WithRequestForStaticFile_ReturnsImmediately() { // arrange var module = new AuthenticationModule(); var httpContext = new Mock <HttpContextBase>(); httpContext.Setup(c => c.Request.Cookies).Throws(new InvalidOperationException()); var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false, RequestLocation.StaticFile, "/"); // act, assert module.AuthenticateRequest(httpContext.Object, blogRequest); }
public TokenResponse GenerateToken([FromBody] User user) { if (ModelState.IsValid) { return(new TokenResponse { Status = "Success", JwtToken = AuthenticationModule.GenerateToken(user.UserName), Message = "Token generated successfully." }); } return(null); }
public static bool GenerateToken(LoginUserValidation user) { UserDetailsModel securityModel = new UserDetailsModel() { UserId = user.UserId, UserName = user.UserName, RoleId = user.RoleId }; var isLogined = !string.IsNullOrEmpty(AuthenticationModule.GenerateTokenForUser(securityModel)); return(isLogined); }
public HttpResponseMessage LoginDemo([FromBody] User user) { if (user == null) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User", Configuration.Formatters.JsonFormatter)); } else { AuthenticationModule authentication = new AuthenticationModule(); string token = authentication.GenerateTokenForUser(user.Username, user.UserId); return(Request.CreateResponse(HttpStatusCode.OK, new { token = token, username = user.Username }, Configuration.Formatters.JsonFormatter)); } }
private void SetUp() { const string Original = @"original.config"; const string OriginalMono = @"original.mono.config"; if (Helper.IsRunningOnMono()) { File.Copy("Website1/original.config", "Website1/web.config", true); File.Copy(OriginalMono, Current, true); } else { File.Copy("Website1\\original.config", "Website1\\web.config", true); File.Copy(Original, Current, true); } Environment.SetEnvironmentVariable( "JEXUS_TEST_HOME", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); _server = new IisExpressServerManager(Current); _serviceContainer = new ServiceContainer(); _serviceContainer.RemoveService(typeof(IConfigurationService)); _serviceContainer.RemoveService(typeof(IControlPanel)); var scope = ManagementScope.Site; _serviceContainer.AddService(typeof(IControlPanel), new ControlPanel()); _serviceContainer.AddService(typeof(IConfigurationService), new ConfigurationService(null, _server.Sites[0].GetWebConfiguration(), scope, null, _server.Sites[0], null, null, null, _server.Sites[0].Name)); _serviceContainer.RemoveService(typeof(IManagementUIService)); var mock = new Mock <IManagementUIService>(); mock.Setup( action => action.ShowMessage( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <MessageBoxButtons>(), It.IsAny <MessageBoxIcon>(), It.IsAny <MessageBoxDefaultButton>())).Returns(DialogResult.Yes); _serviceContainer.AddService(typeof(IManagementUIService), mock.Object); var module = new AuthenticationModule(); module.TestInitialize(_serviceContainer, null); _feature = new BasicAuthenticationFeature(module); _feature.Load(); }
private void btnLogin_Click(object sender, System.EventArgs e) { AuthenticationModule am = (AuthenticationModule)this.Context.ApplicationInstance.Modules["AuthenticationModule"]; if (am.AuthenticateUser(txtUsername.Text, txtPassword.Text, false)) { Context.Response.Redirect(FormsAuthentication.GetRedirectUrl(this.User.Identity.Name, false)); } else { this.lblError.Text = "Invalid username or password."; this.lblError.Visible = true; } }
public void GetFormsAuthenticationTicket_WithRequestHavingIndecipherableAuthCookies_ReturnsNull() { // arrange var module = new AuthenticationModule(); var badCookie = new HttpCookie(".ASPXAUTH.42") { Value = "STEOHsuthosaeuthoes234234sThisIsGarbage", Expires = DateTime.Now }; // act var ticket = module.GetFormsAuthenticationTicket(badCookie); // assert Assert.IsNull(ticket); }
public void GetFormsAuthenticationTicket_WithRequestHavingNullAuthTicket_ReturnsNull() { // arrange var module = new AuthenticationModule(); var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = null }; // act var ticket = module.GetFormsAuthenticationTicket(authCookie); // assert Assert.IsNull(ticket); }
public void Load_Extensions_AllExtensionsWereMapped() { var module = new AuthenticationModule(); PortalApplication.Setup(m => m.GetSettings<AuthenticationSettings>("Authentication")).Returns(Make_AuthenticationSettings()); module.Load(PortalApplication.Object); PortalApplication.Verify(m => m.MapRoute("/v5/EmailPassword", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v5/SecureCookie", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v6/EmailPassword", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v6/AuthKey", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v6/OAuth", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v6/Wayf", It.IsAny<Func<IExtension>>())); PortalApplication.Verify(m => m.MapRoute("/v6/Facebook", It.IsAny<Func<IExtension>>())); }
public ActionResult Login(LoginViewModel model, string returnUrl) { string errorMsg = ""; if (ModelState.IsValid) { bool isLoginSc = AuthenticationModule.AuthenticateUser(model.LoginName, model.Password, ref errorMsg); if (isLoginSc) { return(RedirectToAction("Index", "Aplication")); } ViewBag.errorMsg = errorMsg; } return(View(model)); }
public HttpResponseMessage LoginDemo(LoginProfile loginProfile) { MockAuthenticationService demoService = new MockAuthenticationService(); UserProfile user = demoService.GetUser(loginProfile.Username, loginProfile.Password); if (user == null) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User", Configuration.Formatters.JsonFormatter)); } else { AuthenticationModule authentication = new AuthenticationModule(); string token = authentication.GenerateTokenForUser(user.UserName, user.UserId); return(Request.CreateResponse(HttpStatusCode.OK, token, Configuration.Formatters.JsonFormatter)); } }
public void OnUserInfoUpdate_GivenInfo_ShouldNotInvokeListenerWithDifferentType() { var module = new AuthenticationModule(); var userGuid = new Guid("10000000-0000-0000-0000-000000000001"); var userInfo = 5; UserInfoUpdate<uint> result = null; Action<UserInfoUpdate<uint>> callback = i => result = i; PortalApplication.Setup(m => m.GetSettings<AuthenticationSettings>("Authentication")).Returns(Make_AuthenticationSettings()); module.Load(PortalApplication.Object); module.AddUserInfoUpdateListener(callback); module.OnUserInfoUpdate(userGuid, userInfo); Assert.That(result, Is.Null); }
public IHttpActionResult Login(UserLoginDTO _user) { var user = _db.Users.Where(u => u.Username == _user.Username && u.Password == _user.Password).ToList(); if (user != null && user.Count == 1) { AuthenticationModule auth = new AuthenticationModule(); var token = auth.GenerateTokenForUser(user[0].Username, user[0].ID); return(Ok(token)); } else { return(BadRequest()); } }
public static User GetUserFromToken() { // Get User form Token string token = AuthenticationModule.GetToken(); User result = new User(); if (!string.IsNullOrEmpty(token)) { IClaimsIdentity claim = AuthenticationModule.GetClaim(token); result.UserId = Convert.ToInt16(claim.UserId); result.UserName = claim.UserName; result.RoleId = Convert.ToInt16(claim.RoleId); } return(result); }
public void TokenValidation() { AuthenticationModule authentication = new AuthenticationModule(); string token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbi50ZXN0Iiwibm9tIjoiQWRtaW5pc3RyYXRldXIiLCJwcmVub20iOiJBZG1pbmlzdHJhdGV1ciIsIm1haWwiOiJhZG1pbi5yZXNlYXVAbW9udHBlbGxpZXItZXBzaS5mciIsImNsYXNzZSI6IkFkbWluaXN0cmF0aW9uIiwicm9sZXMiOiJST0xFX1NVUEVSX0FETUlOIiwiaWF0IjoxNTQ0Nzc3NzgzLCJleHAiOjE1NDQ3ODQ5ODN9.ebNHIHnaOtiCTPJmP2a0V7vhkrCZB0S5-wpN2fkzOKk"; JwtSecurityToken securityToken = authentication.ValidateToken(token); Assert.IsNotNull(securityToken); JWTAuthenticationIdentity identity = AuthenticationModule.PopulateUserIdentity(securityToken); Assert.IsTrue(identity.Name.Equals("admin.test")); Assert.IsTrue(identity.Nom.Equals("Administrateur")); Assert.IsTrue(identity.Mail.Equals("*****@*****.**")); Assert.IsTrue(1 == 1); }
public HttpResponseMessage Login(Login login) { var user = _repository.GetAllUsers() .FirstOrDefault(u => u.UserName == login.UserName && u.Password == login.Password); if (user == null) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid User", Configuration.Formatters.JsonFormatter)); } else { AuthenticationModule authentication = new AuthenticationModule(); string token = authentication.GenerateTokenForUser(user.UserName, user.Id); return(Request.CreateResponse(HttpStatusCode.OK, token, Configuration.Formatters.JsonFormatter)); } }
public HttpResponseMessage Post([FromBody] LoginViewModel ViewModel) { try { if (ViewModel == null) { return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Campos Inválidos", "text/plain")); } if (ModelState.IsValid) { var user = _UserRepo.GetByEmail(ViewModel.email); if (user == null) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario Inexistente", "text/plain")); } else { if (Hashing.ValidatePassword(ViewModel.password, user.Password)) { Helper.AtualizarOrdens(user); AuthenticationModule authentication = new AuthenticationModule(); string token = authentication.CreateToken(user.Id, user.Email); //adiciona monitoramento das das ordems e saldos do usuario if (user.BinanceAPIKey != null && user.BinanceAPISecret != null && user.IsValidBinanceKeys) { WSMonitor monitor = WSMonitor.Instancia; monitor.AddMonitor(user); //monitor.RemoveDoubleConnection(user.Id); } return(Request.CreateResponse(HttpStatusCode.OK, token)); } else { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Senha Inválida", "text/plain")); } } } var errorObj = ModelStateErrors.DisplayModelStateError(ModelState); return(Request.CreateResponse(HttpStatusCode.NotAcceptable, errorObj, "text/plain")); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public WeatherForecast Get(int id) { JWTAuthenticationIdentity jwtUser = AuthenticationModule.PopulateUser(HttpContext.User.Identity as ClaimsIdentity); Console.WriteLine($"WeatherForecastController.Get, jwtUser.Name={jwtUser.Name}"); LogManager.GetLogger().Info($"WeatherForecastController.Get, jwtUser.Name={jwtUser.Name}"); var rng = new Random(); return(new WeatherForecast { Date = DateTime.Now.AddDays(2), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)], Roles = String.Join(",", jwtUser.Roles), Email = jwtUser.Mail, Classe = jwtUser.Classe }); }
public async void ItGetsToken() { var module = new AuthenticationModule(); var subscription = new Subscription { Endpoint = new Uri("https://requestb.in/19swc1r1"), Auth = new Auth { Endpoint = new Uri("http://localhost:4050/connect/token"), ClientId = "testclient", ClientSecret = "verysecret" } }; var token = await module.GetToken(subscription, "0", CancellationToken.None); Assert.False(token.token.IsNullOrEmpty()); Assert.Equal("Bearer", token.scheme); }
public void HandleFormsAuthenticationTicket_WithRequestHavingNullAuthTicket_WritesExpiredCookie() { // arrange Func <BlogRequest, HttpContextBase, string> loginFunc = (r, c) => "/foo/login.aspx"; var module = new AuthenticationModule(); var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = null }; var cookies = new HttpCookieCollection { authCookie }; var httpContext = new Mock <HttpContextBase>(); httpContext.Stub(c => c.User); httpContext.Setup(c => c.Request.Path).Returns("/"); httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection()); httpContext.Setup(c => c.Request.Cookies).Returns(cookies); httpContext.Setup(c => c.Response.Redirect(It.IsAny <string>(), true)); var responseCookies = new HttpCookieCollection(); httpContext.Setup(c => c.Response.Cookies).Returns(responseCookies); var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false, RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } }; // act module.HandleFormsAuthenticationTicket(blogRequest, httpContext.Object, null); // assert var principal = httpContext.Object.User as GenericPrincipal; Assert.IsNull(principal); Assert.AreEqual(1, responseCookies.Count); HttpCookie cookie = responseCookies[".ASPXAUTH.42"]; Assert.IsTrue(cookie.Expires.AddYears(20) < DateTime.Now); }
public TokenResponse Validate(string jwtToken, string userName) { string message; var tokenUsername = AuthenticationModule.ValidateToken(jwtToken, out message); if (userName.Equals(tokenUsername)) { return(new TokenResponse { Status = "Success", Message = "User validated successfully." }); } return(new TokenResponse { Status = "Invalid", Message = message }); }
public void AuthenticateRequest_WithRequestHavingValidAuthCookies_SetsUserToGenericPrincipalWithRoles() { // arrange var module = new AuthenticationModule(); const string roles = "Admins|HostAdmins|Users"; var ticket = new FormsAuthenticationTicket(1, ".ASPXAUTH.42", DateTime.Now, DateTime.Now.AddDays(60), true, roles); string cookieValue = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = cookieValue }; var cookies = new HttpCookieCollection { authCookie }; var httpContext = new Mock <HttpContextBase>(); httpContext.Stub(c => c.User); httpContext.Setup(c => c.Request.Path).Returns("/"); httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection()); httpContext.Setup(c => c.Request.Cookies).Returns(cookies); httpContext.Setup(c => c.Response.Cookies).Returns(cookies); var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false, RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } }; // act module.AuthenticateRequest(httpContext.Object, blogRequest); // assert var principal = httpContext.Object.User as GenericPrincipal; Assert.IsNotNull(principal); Assert.IsTrue(principal.IsInRole("Admins")); Assert.IsTrue(principal.IsInRole("HostAdmins")); Assert.IsTrue(principal.IsInRole("Users")); }
public void GetFormsAuthenticationTicket_WithRequestHavingExpiredAuthCookies_SetsUserToGenericPrincipalWithRoles() { // arrange var module = new AuthenticationModule(); const string roles = "Admins|HostAdmins|Users"; var ticket = new FormsAuthenticationTicket(1, ".ASPXAUTH.42", DateTime.Now, DateTime.Now.AddDays(-10), true, roles); Assert.IsTrue(ticket.Expired); string cookieValue = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = cookieValue }; // act var authTicket = module.GetFormsAuthenticationTicket(authCookie); // assert Assert.IsNull(authTicket); }
protected void btnLogin_Click(object sender, System.EventArgs e) { AuthenticationModule am = (AuthenticationModule)Context.ApplicationInstance.Modules["AuthenticationModule"]; if (this.txtUsername.Text.Trim().Length > 0 && this.txtPassword.Text.Trim().Length > 0) { try { if (am.AuthenticateUser(this.txtUsername.Text, this.txtPassword.Text, this.chkPersistLogin.Checked)) { this.lblLoggedInUser.Text = this.txtUsername.Text; this.pnlUserInfo.Visible = true; this.pnlLogin.Visible = false; } else { this.lblLoginError.Text = base.GetText("USERNAMEPASSWORDERROR"); } } catch (Exception ex) { this.lblLoginError.Text = base.GetText("LOGINERROR") + " " + ex.Message; } } else { this.lblLoginError.Text = base.GetText("USERNAMEPASSWORDMISSING"); } if (this.lblLoginError.Text.Length > 0) { this.lblLoginError.Visible = true; } else { // Redirect to self to refresh rendering of the page because this event happens after // everything is already constructed. Context.Response.Redirect(Context.Request.RawUrl); } }
public HttpResponseMessage Post(LoginModel loginModel) { try { UserManager objManager = new UserManager(); var user = objManager.ValidateUser(loginModel.Username, loginModel.Password); if (user == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Incorrect credentials.")); } var authModule = new AuthenticationModule(); string token = authModule.GenerateTokenForUser(user); return(Request.CreateResponse(HttpStatusCode.OK, new { Token = token, Expires = DateTime.UtcNow.AddDays(30) })); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } }