private static void LoginToDefault(OAuthGrantResourceOwnerCredentialsContext context, IFormCollection formValues, string clientId, string country, string username) { ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName.Trim())); oAuthIdentity.AddClaim(new Claim("role", "user")); oAuthIdentity.AddClaim(new Claim("clientId", clientId)); oAuthIdentity.AddClaim(new Claim("country", country)); string brand = formValues.Get("brand"); string shop = formValues.Get("shop"); if (!string.IsNullOrWhiteSpace(brand)) { oAuthIdentity.AddClaim(new Claim("brand", brand)); } if (!string.IsNullOrWhiteSpace(shop)) { oAuthIdentity.AddClaim(new Claim("shop", shop)); } AuthenticationProperties properties = new AuthenticationProperties(new Dictionary <string, string> { { "username", username } }); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); }
public void ReadFromStreamTwice() { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(OriginalFormsString); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); IOwinRequest request = new OwinRequest(); request.Body = stream; IFormCollection form = request.ReadFormAsync().Result; Assert.Equal("v1", form.Get("q1")); Assert.Equal("v2,b", form.Get("Q2")); Assert.Equal("v3,v4", form.Get("q3")); Assert.Null(form.Get("q4")); Assert.Equal("v5,v5", form.Get("Q5")); form = request.ReadFormAsync().Result; Assert.Equal("v1", form.Get("q1")); Assert.Equal("v2,b", form.Get("Q2")); Assert.Equal("v3,v4", form.Get("q3")); Assert.Null(form.Get("q4")); Assert.Equal("v5,v5", form.Get("Q5")); }
async Task <ConsentAnswer> TryGetConsentAnswerAsync(IOwinRequest request) { ConsentAnswer consentAnswer; if (request.IsPost()) { IFormCollection formCollection = await request.ReadFormAsync(); string consent = formCollection.Get(_options.HandleConsentOptions.ConsentParameterName); consentAnswer = ConsentAnswer.TryParse(consent); } else if (request.IsGet()) { string consent = request.Query.Get(_options.HandleConsentOptions.ConsentParameterName); consentAnswer = ConsentAnswer.TryParse(consent); } else { consentAnswer = ConsentAnswer.InvalidMethod; } return(consentAnswer); }
public void ParseForm() { IDictionary <string, object> environment = new Dictionary <string, object>(); environment["owin.RequestBody"] = new MemoryStream(Encoding.ASCII.GetBytes(OriginalFormsString)); IOwinRequest request = new OwinRequest(environment); IFormCollection form = request.ReadFormAsync().Result; Assert.Equal("v1", form.Get("q1")); Assert.Equal("v2,b", form.Get("Q2")); Assert.Equal("v3,v4", form.Get("q3")); Assert.Null(form.Get("q4")); Assert.Equal("v5,v5", form.Get("Q5")); }
public void Get_Merged() { IFormCollection form = CreateForm(RawValues); string values = form.Get(FormsItemKey); Assert.Equal(JoinedValues, values); }
private bool ValidAntiForgeryTokens(IFormCollection form) { //Use the existing cookie if there is one. There may still end up being two (different paths), but this will reduce that chance. //Would we want to delete our own pathed cookie if there is one further up? var cookieToken = Request.Cookies[Options.AntiForgeryCookieName]; var methodToken = Options.GetAntiForgeryToken != null ? Options.GetAntiForgeryToken(Request) : form.Get(Options.AntiForgeryFieldName); if (String.IsNullOrEmpty(cookieToken) || String.IsNullOrEmpty(methodToken)) { return(false); } try { AntiForgery.Validate(cookieToken, methodToken); return(true); } catch (System.Web.Mvc.HttpAntiForgeryException)//System.Web.Helpers.HttpAntiForgeryException??? { return(false); } }
public void GetMissing_null() { IFormCollection form = CreateForm(null); Assert.Null(form[FormsItemKey]); Assert.Null(form.Get(FormsItemKey)); Assert.Null(form.GetValues(FormsItemKey)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:4200" }); IFormCollection parameters = await context.Request.ReadFormAsync(); string email = parameters.Get("email"); string password = parameters.Get("password"); var user = userAppService.Authentication(new LoginAuthenticationDTO() { Email = email, Password = password }); if (user == null) { context.SetError("invalid_grant", "The user email or password is incorrect."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("email", email)); identity.AddClaim(new Claim("role", "user")); identity.AddClaim(new Claim("id", user.Id.ToString())); var props = new AuthenticationProperties(new Dictionary <string, string> { { "id", user.Id.ToString() }, { "name", user.Name }, { "email", user.Email } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
private void LoginToWarehousePickingApp(OAuthGrantResourceOwnerCredentialsContext context, IFormCollection formValues, string clientId, string country) { string mac = formValues.Get("mac"); string brand = formValues.Get("brand"); string shop = formValues.Get("shop"); ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, mac.Trim())); oAuthIdentity.AddClaim(new Claim("role", "user")); oAuthIdentity.AddClaim(new Claim("role", "user")); oAuthIdentity.AddClaim(new Claim("mac", mac)); oAuthIdentity.AddClaim(new Claim("clientId", clientId)); oAuthIdentity.AddClaim(new Claim("country", country)); oAuthIdentity.AddClaim(new Claim("brand", brand)); oAuthIdentity.AddClaim(new Claim("shop", shop)); AuthenticationProperties properties = new AuthenticationProperties(new Dictionary <string, string> { { "username", mac } }); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { ApplicationUserManager storeUserMgr = context.OwinContext.Get <ApplicationUserManager>("AspNet.Identity.Owin:" + typeof(ApplicationUserManager).AssemblyQualifiedName); user = await storeUserMgr.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The username or password is incorrect"); } else if (!user.EmailConfirmed) { context.SetError("invalid_grant", "Please activate your account by clicking on the link sent to your email at registration"); } else if (user.EmployeeStatus.Equals("Terminated")) { context.SetError("invalid_grant", "This account has been disabled"); } else if (((DateTime)user.LastPasswordChangedDate).AddDays(90) < DateTime.Now) { context.SetError("invalid_grant", "Your PassWord Has Expired , Please Change Your Password In Forgot Password Link"); } else { ClaimsIdentity ident = await storeUserMgr.CreateIdentityAsync(user, "Custom"); ///// device code for user login /////// IFormCollection parameters = await context.Request.ReadFormAsync(); var deviceId = parameters.Get("device_id"); user.DeviceCode = deviceId; storeUserMgr.Update(user); AuthenticationTicket ticket = new AuthenticationTicket(ident, new AuthenticationProperties()); context.Validated(ticket); context.Request.Context.Authentication.SignIn(ident); } }
public string GetString(string name) { var urlValue = urlData.Get(name); var formValue = formData.Get(name); if (string.IsNullOrWhiteSpace(urlValue)) { return(formValue); } if (string.IsNullOrWhiteSpace(formValue)) { return(urlValue); } return(string.Format("{0},{1}", urlValue, formValue)); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { if (Request.Path == new PathString("/api/Account/SSOLogon")) { if (string.Equals(this.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(this.Request.ContentType) && (this.Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && this.Request.Body.CanRead)) { if (!this.Request.Body.CanSeek) { this._logger.WriteVerbose("Buffering request body"); MemoryStream memoryStream = new MemoryStream(); await this.Request.Body.CopyToAsync((Stream)memoryStream); memoryStream.Seek(0L, SeekOrigin.Begin); this.Request.Body = (Stream)memoryStream; } IFormCollection form = await this.Request.ReadFormAsync(); //ToDo: clean up get the associated request var protocolFactory = this._resolver.Resolve <Func <string, IProtocolHandler> >(); var protocolHanlder = protocolFactory(Bindings.Http_Post); var protocolContext = new SamlProtocolContext { ResponseContext = new HttpPostResponseContext { AuthenticationMethod = base.Options.AuthenticationType, Form = form.ToDictionary(x => x.Key, v => form.Get(v.Key)) as IDictionary <string, string> } }; await protocolHanlder.HandleResponse(protocolContext); var responseContext = protocolContext.ResponseContext as HttpPostResponseContext; var identity = responseContext.Result; if (identity != null) { return(new AuthenticationTicket(identity, new AuthenticationProperties())); } } } return(null); }
async Task <string> TryGetRawJwtTokenAsync(OAuthAuthorizeEndpointContext context) { string jwt; if (context.Request.IsPost()) { IFormCollection formCollection = await context.Request.ReadFormAsync(); jwt = formCollection.Get(_options.JwtOptions.JwtTokenParameterName); } else if (context.Request.IsGet()) { jwt = context.Request.Query.Get(_options.JwtOptions.JwtTokenParameterName); } else { jwt = ""; } return(jwt); }
/// <summary> /// Предоставляет авторизацию на доступ к ресурсам /// используя identity.AddClaim /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); IFormCollection data = await context.Request.ReadFormAsync(); string UserName = context.UserName; string UserPassword = context.Password; string UserPhone = data.Get("phone"); User user = Credentails.Authenticate(UserName, UserPhone, UserPassword); if (user != null) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, $"{user.UserInfo.LastName} {user.UserInfo.Name}")); identity.AddClaim(new Claim(ClaimTypes.Email, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); List <string> rolesNames = new List <string>(); foreach (AccessRoleType role in Enum.GetValues(typeof(AccessRoleType))) { if (user.AccessRoles.Role.HasFlag(role) && (role != AccessRoleType.None)) { rolesNames.Add(role.ToString()); identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); } } var principal = new GenericPrincipal(identity, rolesNames.ToArray()); Thread.CurrentPrincipal = principal; context.Validated(identity); _userRepository.UpdateLastEnter(user.Id, DateTime.Now); return; } context.SetError("invalid_grant", "User name or password were not recognized"); return; }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); IFormCollection parameters = await context.Request.ReadFormAsync(); var puId = parameters.Get("PuId"); //AppDb db = new AppDb(); //var user = db.Users.FirstOrDefault( q=> q.name == context.UserName && q.pas == context.Password); if (context.UserName == "Test" && context.Password == "Test") { string dateNow = DateTime.Now.ToString(); identity.AddClaim(new Claim(ClaimTypes.Name, "Test")); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1")); identity.AddClaim(new Claim("CompanyId", "12")); identity.AddClaim(new Claim("PuId", puId)); identity.AddClaim(new Claim("TokenDate", dateNow)); //var roles = user.UserPermissions.ToList(); //foreach (var role in roles) //{ // identity.AddClaim(new Claim(ClaimTypes.Role, role.Role.Name)); //} context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } }
/// <summary> /// Grant resource owner credentials overload method. /// </summary> /// <param name="context">Context parameter</param> /// <returns>Returns when task is completed</returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // Initialization. string usernameVal = (String.IsNullOrEmpty(context.UserName)) ? "" : context.UserName; string passwordVal = (String.IsNullOrEmpty(context.Password)) ? "" : context.Password; //var user = this.databaseManager.LoginByUsernamePassword(usernameVal, passwordVal).ToList(); IFormCollection parameters = await context.Request.ReadFormAsync(); string deviceDetails = parameters.Get("DeviceDetails"); deviceDetails = (String.IsNullOrEmpty(deviceDetails)) ? "" : deviceDetails; string deviceUDID = parameters.Get("DeviceUDID"); deviceUDID = (String.IsNullOrEmpty(deviceUDID)) ? "" : deviceUDID; string deviceTYPE = parameters.Get("DeviceTYPE"); deviceTYPE = (String.IsNullOrEmpty(deviceTYPE)) ? "" : deviceTYPE; string mobileDatetime = parameters.Get("MobileDateTime"); mobileDatetime = (String.IsNullOrEmpty(mobileDatetime)) ? "" : mobileDatetime; string fcmToken = parameters.Get("FcmToken"); fcmToken = (String.IsNullOrEmpty(fcmToken)) ? "" : fcmToken; string serviceTYPE = parameters.Get("ServiceTYPE"); serviceTYPE = (String.IsNullOrEmpty(serviceTYPE)) ? "" : serviceTYPE; Users userobject = new Users(); userobject.userName = usernameVal; userobject.passWord = passwordVal; userobject.deviceDetails = deviceDetails; userobject.deviceUDID = deviceUDID; userobject.deviceTYPE = deviceTYPE; userobject.mobileDatetime = mobileDatetime; userobject.fcmToken = fcmToken; userobject.serviceTYPE = serviceTYPE; string userID = ""; string isLead = ""; string teamIDs = ""; JsonStandardResponse sendOtpResponse = null; if (userobject.serviceTYPE.ToLower() == "login") { /*if (userobject.userName != "admin" || userobject.passWord != "admin") * { * context.SetError("invalid_grant", "The user name or password is incorrect."); * return; * }*/ if (userobject.passWord.Length < 8) { context.SetError("invalid_grant", "Password length must be must be equal or greater than 8 characters."); return; } DateTime dateTime; try { dateTime = DateTime.ParseExact(userobject.mobileDatetime, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture); } catch (FormatException) { context.SetError("invalid_grant", "invalid datetime format required is MM-dd-yyyy HH:mm:ss"); return; } //Login from credentials //Verification. //string Status = new UserProfile().VerifyUserCredentials(userobject, Constants.GetConnectionString()); string Status = new UserProfile().VerifyUserCredentialsFromAD(userobject, Constants.GetConnectionString()); if (Status != "Success") { context.SetError("invalid_grant", Status); return; } new UserProfile().InsertUserFcmToken(userobject, Constants.GetConnectionString()); userobject.passWord = ""; } else if (userobject.serviceTYPE.ToLower() == "adminlogin") { /*if (userobject.userName != "admin" || userobject.passWord != "admin") * { * context.SetError("invalid_grant", "The user name or password is incorrect."); * return; * }*/ if (userobject.passWord.Length < 8) { context.SetError("invalid_grant", "Password length must be must be equal or greater than 8 characters."); return; } DateTime dateTime; try { dateTime = DateTime.ParseExact(userobject.mobileDatetime, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture); } catch (FormatException) { context.SetError("invalid_grant", "invalid datetime format required is MM-dd-yyyy HH:mm:ss"); return; } //Login from credentials //Verification. string Status = new UserProfile().VerifyUserCredentials(userobject, Constants.GetConnectionString()); //string Status = new UserProfile().VerifyUserCredentialsFromAD(userobject, Constants.GetConnectionString()); if (Status != "Success") { context.SetError("invalid_grant", Status); return; } new UserProfile().InsertUserFcmToken(userobject, Constants.GetConnectionString()); userobject.passWord = ""; } else if (userobject.serviceTYPE.ToLower() == "refreshtoken") { //Checks DeviceUDID whether it is logged in or not if (userobject.deviceUDID == "" || userobject.userName == "") { context.SetError("invalid_grant", "device udid or user name cannot be empty!"); return; } //Login Status Verification. Users obj = new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString()); if (obj == null) { context.SetError("invalid_grant", "no session found against device udid and user name!"); return; } } else { context.SetError("invalid_grant", "Invalid Request!"); return; } Users userobj = new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString()); if (userobj != null) { userobject.ID = userobj.ID; Users obj = new UserProfile().getUserByUserNameAndUserID(userobject, Constants.GetConnectionString()); userID = obj.ID; isLead = obj.isLead; //teamDetailsJson = new JavaScriptSerializer().Serialize(obj.teams); teamIDs = string.Join(",", obj.teams.Select(x => x.ID).ToArray()); } var claims = new List <Claim>(); //claims.Add(new Claim("serviceTYPE", userobject.serviceTYPE.ToLower())); //claims.Add(new Claim("userName", usernameVal)); IDictionary <string, string> data = new Dictionary <string, string> { { "serviceTYPE", userobject.serviceTYPE.ToLower() }, { "userName", usernameVal }, { "userID", userID }, { "isLead", isLead }, { "teamIDs", teamIDs } //{ "UserDetails", JsonConvert.SerializeObject(new UserProfile().checkUserLoginStatus(userobject, Constants.GetConnectionString()))} }; // Setting Claim Identities for OAUTH 2 protocol. ClaimsIdentity oAuthClaimIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesClaimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType); AuthenticationTicket ticket = new AuthenticationTicket(oAuthClaimIdentity, new AuthenticationProperties(data)); // Grant access to authorize user. context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesClaimIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { string username = context.UserName?.Trim(); if (username.EqualsIgnoreCaseAndBlank("2298101188")) { username = "******"; } string password = context.Password?.Trim(); IFormCollection formValues = await context.OwinContext.Request.ReadFormAsync(); string clientId = formValues.Get("client_id"); string country = formValues.Get("country") ?? string.Empty; clientId = FixClientId(clientId); if (clientId.EqualsIgnoreCaseAndBlank("WorkFlow")) { LoginToWorkFlow(context, username, password); return; } if (clientId.EqualsIgnoreCaseAndBlank("WHPicking")) { LoginToWarehousePickingApp(context, formValues, clientId, country); return; } if (clientId.EqualsIgnoreCaseAndBlank("ShopAssistant")) { if (Authenticate(username, password, clientId, false)) { await LoginToShopAssistant(context, clientId, username); return; } context.SetError("error", "Invalid username or password or unauthorized"); return; } if (clientId.EqualsIgnoreCaseAndBlank("TKValidation")) { if (Authenticate(username, password)) { DoSimpleLogin(context, username); return; } context.SetError("error", "Invalid username or password or unauthorized"); return; } if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(clientId)) { context.SetError("error", "Username or password is missing"); return; } if (clientId.EqualsIgnoreCaseAndBlank("WarehouseAssistant")) { if (Authenticate(username, password)) { LoginToWarehouseAssistantApp(context, formValues, username, clientId, country); return; } context.SetError("error", "Invalid username or password or unauthorized"); return; } if (clientId.EqualsIgnoreCaseAndBlank("BLSSKU")) { if (Authenticate(username, password)) { LoginToWarehouseAssistantApp(context, formValues, username, clientId, country); return; } context.SetError("error", "Invalid username or password or unauthorized"); return; } if (Authenticate(username, password, clientId)) { LoginToDefault(context, formValues, clientId, country, username); return; } context.SetError("error", "Invalid username or password or unauthorized"); }
public string GetUsername() { return(_form.Get("username")); }
private LoginType DetectLoginType(IFormCollection form) { if (!string.IsNullOrEmpty(form.Get("grant_type")) && form.Get("grant_type").Equals("refresh_token")) return LoginType.RefreshToken; if (!string.IsNullOrEmpty(form.Get("cauthorization"))) return LoginType.LoginApiKey; return !string.IsNullOrEmpty(form.Get("deviceKey")) ? LoginType.LoginDevice : LoginType.LoginForm; }