Asp.Net application with DropBox not working - asp.net

I set the DropBox application type Full DropBox; I set on my application the following function:
Private Const AppKey As String = "my key"
Private Const AppSecret As String = "my secret"
Private Function Upload() As String
Dim client As DropNetClient
Dim token As UserLogin
Dim userToken As String = My.Settings.userToken
Dim userSecret As String = My.Settings.userSecret
Dim needAccessToken As Boolean = (String.IsNullOrEmpty(userToken) Or String.IsNullOrEmpty(userSecret))
If (needAccessToken) Then
client = New DropNet.DropNetClient(AppKey, AppSecret)
client.UseSandbox = True
client.GetToken()
Dim url = client.BuildAuthorizeUrl()
Try
token = client.GetAccessToken()
Catch ex As Exception
Console.WriteLine("Exception! " + ex.Message)
Exit Function
End Try
userToken = token.Token
userSecret = token.Secret
My.Settings.Properties.Item("userToken").DefaultValue = userToken
My.Settings.Properties.Item("userSecret").DefaultValue = userSecret
My.Settings.Save()
Else
client = New DropNet.DropNetClient(AppKey, AppSecret, userToken, userSecret)
client.UseSandbox = True
End If
Dim rawData As Byte() = File.ReadAllBytes(Server.MapPath("") + "/Fax/" + "Fax.zip")
Dim result As MetaData = client.UploadFile("/", "fax.zip", rawData)
End Function
Unfortunately education tokens = GetAccessToken () I get the error:
Received Response [Unauthorized]: Expected to see [OK]. The HTTP response was [{" "error" ":" "Request token has not been properly authorized by a user. ""}] ".
I checked the URL (client.BuildAuthorizedUrl ()) and returns me "Unauthorized".
How can I link to Dropbox folder? I do something wrong? Or do I need to set better application of Dropbox?

Once you get the URL via BuildAuthorizeUrl, you need to send the user to that address and have them authorize your app. Only once they've done that can you call GetAccessToken.
The error you're seeing is because you're trying to get the access token before the user has actually authorized your app.

Related

API 400 error Username required Password required

I am sending JSON data to external API as following :
Dim url = "https://********"
Dim _httpClient = New HttpClient()
_httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("MyUsername", "MyPassword")
Using content = New StringContent(json, System.Text.Encoding.UTF8, "application/json")
Dim result As HttpResponseMessage = _httpClient.PostAsync(url, content).Result
If result.StatusCode = System.Net.HttpStatusCode.Created Then
Console.WriteLine(result.StatusCode)
Return True
End If
but I am receiving the following error:
{"status":400,"message":"Invalid Request","data":[{"field":"username","message":"Username required"},{"field":"password","message":"Password required"}]}
how to fix this issue ?
As per your API definition it is expecting username and password in the header as key value pair. you can add them like this.
_httpClient.DefaultRequestHeaders.Add("Username", "MyUsername");
_httpClient.DefaultRequestHeaders.Add("password", "MyPassword");

Microsoft Graph API Forbiden

Imports Microsoft.Graph
Imports Azure.Identity
Module Module1
Sub Main()
Dim onlineMeeting = New OnlineMeeting With {
.StartDateTime = DateTimeOffset.Parse("2022-04-23T21:33:30.8546353+00:00"),
.EndDateTime = DateTimeOffset.Parse("2022-04-23T22:03:30.8566356+00:00"),
.Subject = "Application Token Meeting",
.Participants = New MeetingParticipants With {
.Organizer = New MeetingParticipantInfo With {
.Identity = New IdentitySet With {
.User = New Identity With {
.Id = "ba525532-764a-4aa1-8103-066beca0f5a8"
}
}
}
}
}
Dim testing As Task(Of OnlineMeeting) = createMeeting(onlineMeeting)
Console.WriteLine(testing.Status.ToString)
Console.ReadKey()
End Sub
Public Async Function createMeeting(onlineMeeting As OnlineMeeting) As Task(Of OnlineMeeting)
Dim createMeetings As OnlineMeeting = Nothing
Try
Dim clientId As String = "XXXXXXXXX"
Dim clientSecret As String = "XXXXXXXXXXXXX"
Dim tenantId As String = "XXXXXXXXXXX"
Dim options = New TokenCredentialOptions With
{
.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
}
Dim ClientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)
Dim graphClient As GraphServiceClient = New GraphServiceClient(ClientSecretCredential)
createMeetings = Await graphClient.Communications.OnlineMeetings.Request().AddAsync(onlineMeeting)
Catch ex As ServiceException
Console.WriteLine(ex.RawResponseBody)
End Try
Return createMeetings
End Function
End Module
When i execute this i get :
WaitingForActivation
{"error":{"code":"Forbidden","message":"","innerError":{"request-id":"XXXXX","date":"2021-08-27T11:38:30","client-request-id":"XXXXXXXX"}}}
Can someone help me?
This normally means there is no permission to perform the action.
Check you are including the relavent scope when authenticating against graph. In this case it is 'OnlineMeetings.ReadWrite' for delegated permissions and 'OnlineMeetings.ReadWrite.All' for application permissions
If using delegated permissions check the delegated user has permission to perform this action, if they can't do it manually you can't do it through graph.
If using application permissions make sure you have created an appropriate application access policy as described in the blue note here: https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=http
Administrators must create an application access policy and grant it to a user, authorizing the app configured in the policy to create an online meeting on behalf of that user (user ID specified in the request path).

Cannot delete a file on server using ftp from asp.net

I have created an asp.net application to maintain images for a shopping site, it includes 2 functions, one for uploading the image via ftp and the other for deleting the image using ftp.
I can upload files without an issue but when I try to delete a file I get the response "The remote server returned an error: (530) Not logged in."
I'm using the same ftpuri and credentials so I'm a little confused as to why it doesn't work.
Here's the code for the upload which works.
Upload Section :
Dim ftpRequest As FtpWebRequest = CType(WebRequest.Create(ftpuri), FtpWebRequest)
Try
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.Credentials = New NetworkCredential(ftpusername, ftppassword)
Dim bytes() As Byte = System.IO.File.ReadAllBytes(filetoupload)
ftpRequest.ContentLength = bytes.Length
Using UploadStream As Stream = ftpRequest.GetRequestStream()
UploadStream.Write(bytes, 0, bytes.Length)
UploadStream.Close()
End Using
Catch ex As Exception
End Try
Here's the code for the delete that fails with the error The remote server returned an error: (530) Not logged in.
Delete Section:
Dim ftpRequest As FtpWebRequest = CType(WebRequest.Create(ftpUri), FtpWebRequest)
Try
ftpRequest.Credentials = New NetworkCredential(ftpusername, ftppassword)
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile
Dim responseFileDelete As FtpWebResponse = CType(ftpRequest.GetResponse(), FtpWebResponse)
Catch ex As Exception
End Try
In both cases the values in ftpuri, ftpusername and ftppassword are identical.
I can delete the file using ftp software with the same credentials.
Any help would be appreciated.
Ron
Try this way :
public bool DeleteFileFromFtpServer(Uri serverUri, string ftpUsername, string ftpPassword)
{
try
{
// The serverUri should look like this ftp:// scheme.
// It contains server name along with file name that will be deleted.
// eg: ftp://abc.com/test.txt.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
Calling:
obj.DeleteFileFromFtpServer(new Uri (toDelFilename), user,pass);

Asp.net UseOpenIdConnectAuthentication not working in Azure

I am using UseOpenIdConnectAuthentication to authenticate users. My application code works fine locally. But, when I run it on Azure, the SecurityTokenValidated event is never fired. Consequently, the code runs fine but the user is never authenticated. I am not sure if the issue is with my code or with Azure. This is being used in a Web Form, Asp.net application (not Core). I use the Azure trace feature to log. I can see that only "RedirectToIdentityProvider" is fired. No other event gets called. Here is my code:
Startup.Auth.Vb:
Public Sub ConfigureAuth(app As IAppBuilder)
Dim clientId As String = ""
Dim authority As String = ""
Dim redirectURI As String
Trace.TraceInformation("Hit Config Auth function")
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = New Dictionary(Of String, String)
app.SetDefaultSignInAsAuthenticationType("Cookies")
app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
.AuthenticationMode = AuthenticationMode.Active,
.CookieManager = New SystemWebCookieManager
})
redirectURI = appSettings("ID_Redirect_URI")
clientId = appSettings("ID_ClientID")
authority = appSettings("ID_Authority")
Trace.TraceInformation(redirectURI)
Trace.TraceInformation(clientId)
Trace.TraceInformation(authority)
Trace.TraceInformation("creating OpenIDAuthOptions")
Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
.SignInAsAuthenticationType = "Cookies",
.Authority = authority,
.RequireHttpsMetadata = False,
.ClientId = clientId,
.ResponseType = "id_token",
.Scope = "openid profile roles",
.RedirectUri = redirectURI,
.PostLogoutRedirectUri = redirectURI,
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.AuthenticationFailed = Function(ctx)
Trace.TraceInformation("Auth Failed event")
Return Task.FromResult(0)
End Function,
.SecurityTokenReceived = Function(ctx)
Trace.TraceInformation("Sec Token Recieved event")
Return Task.FromResult(0)
End Function,
.MessageReceived = Function(ctx)
Trace.TraceInformation("Message Recieved event")
Return Task.FromResult(0)
End Function,
.SecurityTokenValidated = Function(ctx)
Trace.TraceInformation("Security token validated")
Return Task.FromResult(0)
End Function,
.AuthorizationCodeReceived = Function(ctx)
Trace.TraceInformation("Auth Code Recieved event")
Return Task.FromResult(0)
End Function,
.RedirectToIdentityProvider = Function(context)
Trace.TraceInformation("start of RedirectToIDProvider")
Return Task.FromResult(0)
End Function
}
}
Trace.TraceInformation("adding OpenIdAuthOptyions")
app.UseOpenIdConnectAuthentication(OpenIdAuthOption)
Trace.TraceInformation("finihsed adding OpenIdAuthOptyions")
End Sub
As I mentioned above, this code works fine locally. It only does not work when hosted on Azure. When running locally, the events are fired in this order:
RedirectToIdentityProvider
Message Received
Security Token Received
Security Token Validated
But, in Azure, only RedirectToIdentityProvider is fired.
Changed your Action to take when request is not authenticated in App Service Authentication/Authorization section in the azure portal from LogIn with Azure Active Directory to Allow Anonymous requests. As shown on the picture below:
Then the SecurityTokenValidated would be fired. App services auth takes place outside of you app, so customized auth code in your app never gets a chance to run. When you turn that off it allows your app to handle the auth itself the same way it does locally.
Here is the similar issue you could refer to.
Try changing the application manifest of the application definition on Azure to set the "oauth2AllowIdTokenImplicitFlow" property to true from false.
Go to the Azure Portal,
Select to Azure Active Directory
Select App Registrations
Select your app.
Click on Manifest
Find the value oauth2AllowIdTokenImplicitFlow and change it's value to true
Click Save
2) In your startup.cs file, change the following:
ResponseType = OpenIdConnectResponseType.Code
to
ResponseType = OpenIdConnectResponseType.CodeIdToken
and see if it helps.

Adding Google Calendar entry without using setUserCredentials

I am following the example provided by Google for Market place app at
http://code.google.com/googleapps/marketplace/tutorial_dotnet.html
I got the google authentication working as in the example ,
My next task is to add a entry to Google calendar. I found following code for that, and it is also working fine
CalendarService service = new CalendarService(APPLICATION_NAME);
service.setUserCredentials(vUserName, vPassword);
Google.GData.Calendar.EventEntry entry = new Google.GData.Calendar.EventEntry();
// Set the title and content of the entry.
entry.Title.Text = title;
entry.Content.Content = contents;
// Set a location for the event.
Where eventLocation = new Where();
eventLocation.ValueString = location;
entry.Locations.Add(eventLocation);
When eventTime = new When(startTime, endTime);
entry.Times.Add(eventTime);
Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
// Send the request and receive the response:
AtomEntry insertedEntry = service.Insert(postUri, entry);
The problem i have is the following line, If i give my username and password it will work
service.setUserCredentials(vUserName, vPassword);
i have authenticated the user as in google example. So I don’t know the username and password of other users login to my site using their gmail.
How do i add a calender entry with the information i have?
I have seen several examples with RequestFactory authenticating the user. but couldn't find complete example that I can use
you will need to create a .pfx cert file and upload it to google and place it on your server.
create your AuthSubRequest URL
<asp:HyperLink ID="GotoAuthSubLink" runat="server"/>
GotoAuthSubLink.Text = "Login to your Google Account";
GotoAuthSubLink.NavigateUrl = AuthSubUtil.getRequestUrl("(return url)http://www.example.com/RetrieveToken", "https://www.google.com/calendar/feeds/", false, true);
after the person clicks on your auth link they are returned to your return url. get your session token as follows
String sessionToken = ""; //Save this for making your calls.
String certFile = "D:\\websites\\yourwebsite.com\\google.pfx";
String result = GetAuthSubSessionToken(Request["token"]);
protected AsymmetricAlgorithm GetRsaKey()
{
X509Certificate2 cert = new X509Certificate2(certFile, "");
RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
return privateKey;
}
public string GetAuthSubSessionToken(string singleUseToken)
{
string gatStr = "";
try
{
AsymmetricAlgorithm rsaKey = GetRsaKey();
try
{
sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, rsaKey).ToString();
gatStr = "Session Token = " + SessionToken;
}
catch (Exception e)
{
gatStr = "Error: I appears that the Google authentication server is experiencing an error. Try the authorizaton link again in a few minutes. <a href=\""
+ rtnUrl + "\" title=\"" + e.Message + "\">continue</a>";
}
}
catch (Exception E)
{
gatStr = "Error: rsa " + E.Message + E.StackTrace;
}
return gatStr;
}
save the session token and use CreateCalendarService in subsequent calls to create your calendar service.
public CalendarService CreateCalendarService()
{
GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "YourName-calendarApp-1");
authFactory.Token = sessionToken;
authFactory.PrivateKey = GetRsaKey();
CalendarService cs = new CalendarService(authFactory.ApplicationName);
cs.RequestFactory = authFactory;
return cs;
}

Resources