asp.net membership provider fails on changepassword when passwordformat moved from clear to hash - hash

I have an old application using asp.net membership for logins (upgraded to .netframework4.8). I have successfully enabled passwordformat from clear to hashed for a new user.
Now there is a need to redirect existing users to changepassword page where they can successfully upgrade their passwords.
I assumed it would work as expected but somehow I get
Also, it does not hit the buttonclick event in debugger so I assume its some inbuilt function from the MembershipUser/Membership.Provider class
Protected Sub ChangePassword_Click(sender As Object, e As EventArgs) Handles ChangePassword.Click
Dim msg As String = "Password changed OK"
Try
Dim username As String = Request.QueryString("user")
Dim password As String = NewPassword.Text
If Trim(password) <> "" Then
Dim mu As MembershipUser = Membership.Providers("VLSqlMembershipProvider").GetUser(username, False)
Dim resetPassword As String = mu.ResetPassword()
mu.ChangePassword(resetPassword, password)
Else
Exit Sub
End If
Catch ex As Exception
'msg = ex.Message
msg = "Password does not meet minimum requirements - min 8 characters"
End Try
StatusMessage.Text = msg
End Sub
PS: I have changed newpassword length from 7 to 8

Related

Changing user folder collaborating type in box using Salesforce Toolbox

I'm trying to change Box folder collaboration type for user from salesforce Apex trigger. The first thoughts were to use box.Toolkit but it looks like this class does not have updateCollaboration or changeCollaboration method, only create. I guess my only option is to use Box's Rest API. Is there any way I can get service account token in Apex so I can use it in a callout?
I have created a special "Tokens" object in Salesforce with two fields: access token and refresh token. I then have a batch job that runs to update the access token every 55 minutes such that they never expired.
Here is a code snippet in APEX using the Tokens object.
#future(callout=true)
public static void updateTokens(){
//app info for authenticating
String clientID = 'MY_CLIENT_ID';
String clientSecret = 'MY_CLIENT_SECRET';
//look up value of existing refresh token
Token__c myToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Refresh'];
Token__c myAccessToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Access'];
String refreshToken = myToken.Value__c;
String accessToken = myAccessToken.Value__c;
//variables for storing data
String BoxJSON = '';
String debugTxt = '';
//callout to Box API to get new tokens
HttpRequest reqRefresh = new HttpRequest();
reqRefresh.setMethod('POST');
String endpointRefresh = 'https://www.box.com/api/oauth2/token';
reqRefresh.setEndpoint(endpointRefresh);
String requestBody = ('grant_type=refresh_token&refresh_token=' + refreshToken + '&client_id=' + clientID + '&client_secret=' + clientSecret);
reqRefresh.setBody(requestBody);
System.debug('Body of refresh request: ' + requestBody);
//Create Http, send request
Http httpRefresh = new Http();
Boolean successRefresh = false;
while (successRefresh == false){
try{
HTTPResponse resRefresh = httpRefresh.send(reqRefresh);
BoxJSON = resRefresh.getBody();
System.debug('Body of refresh response: ' + BoxJSON);
successRefresh = true;
}
catch (System.Exception e){
System.debug('Error refreshing: ' + string.valueof(e));
if (Test.isRunningTest()){
successRefresh = true;
}
}
}
Keep in mind that if you are using the Box for Salesforce integration your administrator can set the option for the permissions on the folders to sync with Salesforce permissions. This would reverse any changes you make to collaborations. Check out more about Box's Salesforce integration permissions here: https://support.box.com/hc/en-us/articles/202509066-Box-for-Salesforce-Administration#BfS_admin_perm

Socket.Receive does not receive the data

We have a Classic ASP plus .Net application. We have a .Net page that transfers the session from Classic ASP to .Net. This page uses the Socket class to give call to a classic ASP page that generates XML of the session data. Then it reads that data via Socket and creates the .Net session based on the same.
We have only Windows Authentication enabled in IIS 7.5.
The above page throws the following error:
System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
Parameter name: startIndex
On line:
xml = receive.Substring(receive.IndexOf("<?xml"), receive.Length - receive.IndexOf("<?xml"))
It works fine if we also enable the Anonymous Authentication. However, on doing that the Windows Authentication stops working (as expected). So our problem is, we need only Windows Authentication enabled, but we also need this page to work (which is currently not working in Windows Auth only mode).
I have given below the code from this page. Here, GetSession function get called from another .Net page that needs to session data. This page then generates the session by giving call to GetXML function below.
Public Function getSession(ByVal request As System.Web.HttpRequest, ByVal session As System.Web.SessionState.HttpSessionState)
session.RemoveAll()
'Define the URL and page to load the Session XML from
Dim sName As String = request.ServerVariables("SCRIPT_NAME")
Dim XMLServer As String = request.ServerVariables("SERVER_NAME")
Dim XMLPage As String = Left(sName, InStr(2, sName, "/")) & "ASPSessionXML.asp"
XMLServer = oNet.ComputerName & ".xxxxxxxx.com"
'Define an XMLDocument to allow easy XML tree navigation
Dim doc As XmlDocument = New XmlDocument()
'Load the document from the reader
doc.LoadXml(GetXML(XMLServer, XMLPage, request))
'Loop through the Session element's child nodes and set
'each Session object
Dim node As XmlNode
For Each node In doc.FirstChild.NextSibling.ChildNodes
session(node.Name.ToString()) = System.Web.HttpUtility.UrlDecode(node.InnerText.ToString())
Next
End Function
Public Function GetXML(ByVal server As String, ByVal page As String, ByVal request As System.Web.HttpRequest)
'create socket
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(server)
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim ipe As IPEndPoint = New IPEndPoint(ipAddress, 80)
Dim socket As Socket = New Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)
'connect socket to server
socket.Connect(ipe)
'Create the request to send to the server
Dim strRequest As String
strRequest = "GET /" & page & " HTTP/1.1" & vbCrLf
strRequest = strRequest & "Host: " & server & vbCrLf
strRequest = strRequest & "Connection: Close" & vbCrLf
strRequest = strRequest & "Cookie: " & request.Headers("Cookie") & vbCrLf
strRequest = strRequest & "User-Agent: " & request.Headers("User-Agent") & vbCrLf & vbCrLf
'Convert send data to bytes
Dim bytesSend As Byte() = Encoding.ASCII.GetBytes(strRequest)
'Send the data to the server
socket.Send(bytesSend, bytesSend.Length, 0)
'/**********************************************
'* Receive the returned data
'**********************************************/
'Declare variables for data receipt
Dim bytes(255) As Byte
Dim nBytes As Integer = 0
Dim receive As String = ""
Dim xml As String = ""
Do
nBytes = socket.Receive(bytes, bytes.Length, 0)
receive = receive & Encoding.ASCII.GetString(bytes, 0, nBytes)
Loop While (nBytes > 0)
'We have the page data, but it includes the headers
' Retrieve XML data from page response
xml = receive.Substring(receive.IndexOf("<?xml"), receive.Length - receive.IndexOf("<?xml"))
'Cleanup the socket
socket.Shutdown(SocketShutdown.Both)
socket.Close()
'Return the data
GetXML = xml
End Function

Google API v3 .Net client Unauthorized client or scope in request

I'm getting the error message "Unauthorized client or scope in request." When the following code executes. If I remove the .User = myUserEmail parameter I get a "Insufficient Permission [403]" error message. If I had to guess, I would guess that the issue is the .user parameter I'm using. But, I don't what I'm doing wrong there. I'm using the email address associated with the Google Account I normally use to login to Google Analytics.
Private myClientEmail As String = System.Configuration.ConfigurationManager.AppSettings("clientEmail").ToString()
Private myP12Path As String = System.Configuration.ConfigurationManager.AppSettings("p12Path").ToString()
Private myP12Password As String = System.Configuration.ConfigurationManager.AppSettings("p12Password").ToString()
Private myUserEmail As String = System.Configuration.ConfigurationManager.AppSettings("userEmail").ToString()
Private myApplicationName As String = System.Configuration.ConfigurationManager.AppSettings("applicationName").ToString()
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add("https://www.googleapis.com/auth/drive.readonly")
Dim certificate As X509Certificate2 = New X509Certificate2(myP12Path, myP12Password, X509KeyStorageFlags.Exportable)
Dim credential As ServiceAccountCredential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(myClientEmail) With {
.Scopes = scopes,
.User = myUserEmail
}.FromCertificate(certificate))
Dim service As AnalyticsService = New AnalyticsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = myApplicationName
})
Dim profileId As String = "ga:12345678"
Dim startDate As String = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd")
Dim endDate As String = DateTime.Today.ToString("yyyy-MM-dd")
Dim metrics As String = "ga:visits"
Dim request As DataResource.GaResource.GetRequest = service.Data.Ga.Get(profileId, startDate, endDate, metrics)
request.Dimensions = "ga:date"
Dim data As GaData = request.Execute()
I found the error in my ways...
Somewhere along the lines I inadvertently changed the scope to the "drive.readonly". When I'm trying to work with the "analytics.readonly".

Apple In app purchase verify recurring payment in .NET Java 21002 exception

We are trying to verify a receipt for a RECURRING in-app payment made in iOS.
Referring to an earlier question on stack (http://stackoverflow.com/questions/11085847/keep-getting-21002-java-lang-nullpointerexception-on-apples-verifyreceipt), I manage to use the following code which sends in a JSON object made up of our receipt and sharedSecret key but we get the dreaded {"status":21002, "exception":"java.lang.NullPointerException"} error
Dim json As String ="{'receipt-data':'base64encoded receipt data','password':'YYYY'}"
Dim webRequest = System.Net.HttpWebRequest.Create("https://sandbox.itunes.apple.com/verifyReceipt")
webRequest.ContentType = "text/plain"
webRequest.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(json)
webRequest.ContentLength = byteArray.Length
Using stream = webRequest.GetRequestStream()
stream.Write(byteArray, 0, byteArray.Length)
stream.Flush()
End Using
Dim resp = webRequest.GetResponse()
If resp IsNot Nothing Then
Using sr = New System.IO.StreamReader(resp.GetResponseStream())
Dim result = sr.ReadToEnd().Trim()
' always getting '21002' 'java.lang.NullPointerException'
Response.Write(result.ToString())
End Using
End If
Any help appreciated!

Specflow with MVC Model Validation Issue

I am using Specflow, nunit and moq to test the default MVC2 application registration as I learn SpecFlow.
I have the following steps for checking if the username and password have not been entered.
Steps
[Given(#"The user has not entered the username")]
public void GivenTheUserHasNotEnteredTheUsername()
{
_registerModel = new RegisterModel
{
UserName = null,
Email = "test#dummy.com",
Password = "test123",
ConfirmPassword = "test123"
};
}
[Given(#"The user has not entered the password")]
public void GivenTheUserHasNotEnteredThePassword()
{
_registerModel = new RegisterModel
{
UserName = "user" + new Random(1000).NextDouble().ToString(),
Email = "test#dummy.com",
Password = string.Empty,
ConfirmPassword = "test123"
};
}
[When(#"He Clicks on Register button")]
public void WhenHeClicksOnRegisterButton ()
{
_controller.ValidateModel(_registerModel);
_result = _controller.Register(_registerModel);
}
[Then(#"He should be shown the error message ""(.*)"" ""(.*)""")]
public void ThenHeShouldBeShownTheErrorMessage(string errorMessage, string field)
{
Assert.IsInstanceOf<ViewResult>(_result);
var view = _result as ViewResult;
Assert.IsNotNull(view);
Assert.IsFalse(_controller.ModelState.IsValid);
Assert.IsFalse(view.ViewData.ModelState.IsValidField(field));
Assert.IsTrue(_controller.ViewData.ModelState.ContainsKey(field));
Assert.AreEqual(errorMessage,
_controller.ModelState[field].Errors[0].ErrorMessage);
}
Extension method to force validation
public static class Extensions
{
public static void ValidateModel<T> ( this Controller controller, T modelObject )
{
if (controller.ControllerContext == null)
controller.ControllerContext = new ControllerContext();
Type type = controller.GetType();
MethodInfo tryValidateModelMethod =
type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(
mi => mi.Name == "TryValidateModel" && mi.GetParameters().Count() == 1).First();
tryValidateModelMethod.Invoke(controller, new object[] { modelObject });
}
}`
I do not understand why the password missing test fails on the following lines.
Assert.IsFalse(view.ViewData.ModelState.IsValidField(field));
Assert.IsTrue(_controller.ViewData.ModelState.ContainsKey(field));
I have noticed that the error message being returned is for the Password and ConfirmPassword not matching but I dont understand why for all the other tests, including the Missing Confirm Password test (Identical to the missing Password test) they work fine.
Any ideas?
Features
Scenario: Register should return error if username is missing
Given The user has not entered the username
When He Clicks on Register button
Then He should be shown the error
message "The Username field is required." "username"
Scenario: Register should return error if password is missing
Given The user has not entered the
password
When He Clicks on Register button
Then He should be shown the error message "'Password' must be at least
6 characters long." "Password"
UPDATE
Ok seems the ValidatePasswordLengthAttribute in the Account Model couldn't initilise Membership.Provider as I did not have the connectionstring in my app.config. Is the Pembership.Provider connecting to the membership DB now?
I have added the connection string but now the test passes 50% of the time as it returns two errors:
Password required
Password must be 6 chars long.
The problem is that they are not returned in the same order every time so the test is flaky.
How can I rewrite my scenario and test to account for this? Can I still keep the one "Then" method or do I need to create a new method?
Thanks.
I had to add the connection string the the AccountService to the App.config which nunit uses. This was causing an error on the ValidatePasswordLengthAttribure.
I have updated the Assert which checks for the correct error message to:
Assert.AreEqual(errorMessage,
_controller.ModelState[field].Errors.First(e => e.ErrorMessage == errorMessage).ErrorMessage);
Still unsure about whether the Membership.Provider is hitting the DB