Get authenticated ClientContext with logged in credentials - vb.net

I'm new to using SharePoint. Is it possible to get an authenticated ClientContext without a username and password? I would like to make my app automatically access SharePoint if the machine is already logged in to Office 365 (word,excel,outlook) or to SharePoint in a web browser. I need the authenticated ClientContext so i can pass the credentials to a DownloadFile method.
Private Sub DownloadFile(webUrl As String, credentials As ICredentials, fileRelativeUrl As String)
Using client = New WebClient()
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
client.Headers.Add("User-Agent: Other")
client.Credentials = credentials
client.DownloadFile(webUrl, fileRelativeUrl)
End Using
End Sub
Thanks in advance.

Related

Active Directory: Add New User C# / VB

I browsed other questions and couldn't find the answer.
What is the appropriate way to add a new user to a active directory specific group when the "current user" running the application does not have access rights to add new users?
I am currently authenticating as the domain Administrator to do it, but obviously that is a security no-no and I don't want the Administrator user's credentials hard-codeded in my code.
I assume the answers is not in my code itself but that I have to create a user in the Active Directory that has privileges to add users.
So my question is a combination of a AD and a Coding question:
1) How do I create a AD user that ONLY has access rights to add users to specific OU and CN security group?
2) Is their any way possible to not hard-code the password for this user?
Or... am I going about this entirely wrong?
Here is my current VB.NET code:
Public Function CreateUser(ByVal UserName As String, ByVal Password As String, ByVal DisplayName As String) As Boolean
Try
'Dim catalog As Catalog = New Catalog()
Dim de As DirectoryEntry = New DirectoryEntry()
de.Path = "LDAP://OU=TS2xUsers,DC=dc,DC=example,DC=com"
de.AuthenticationType = AuthenticationTypes.Secure
de.Username = "Administrator"
de.Password = "foopassword"
'1. Create user accountd
Dim users As DirectoryEntries = de.Children
Dim newuser As DirectoryEntry = users.Add("CN=" & DisplayName, "user")
newuser.Properties("givenname").Value = DisplayName
newuser.Properties("name").Value = DisplayName
newuser.Properties("displayName").Value = DisplayName
newuser.Properties("SAMAccountName").Value = UserName
newuser.Properties("userPrincipalName").Value = UserName & "#dc.example.com"
'newuser.Properties("OU").Value = "TS2xUsers"
newuser.CommitChanges()
Dim ret As Object = newuser.Invoke("SetPassword", Password)
newuser.CommitChanges()
Dim exp As Integer = CInt(newuser.Properties("userAccountControl").Value)
exp = exp And Not &H2 'enable acccount
exp = exp Or &H10000 'dont expire password
newuser.Properties("userAccountControl").Value = exp
newuser.CommitChanges()
''' 5. Add user account to groups
If MakeTSUser(newuser) = False Then
Return False
newuser.Close()
de.Close()
End If
newuser.Close()
de.Close()
Return True
Catch ex As Exception
MsgBox("Failed to create user due to the following reason: " & ex.Message, MsgBoxStyle.Critical)
Return False
End Try
End Function
Private Function MakeTSUser(ByVal deUser As DirectoryEntry) As Boolean
Try
Dim deRBGroup As New DirectoryEntry
deRBGroup.Path = "LDAP://CN=TSUsers,CN=Builtin,DC=dc,DC=example,DC=com"
deRBGroup.AuthenticationType = AuthenticationTypes.Secure
deRBGroup.Username = "Administrator"
deRBGroup.Password = "foopassword"
Dim deDomainUsers As New DirectoryEntry
deDomainUsers.Path = "LDAP://CN=Domain Users,CN=Users,DC=dc,DC=example,DC=com"
deDomainUsers.AuthenticationType = AuthenticationTypes.Secure
deDomainUsers.Username = "Administrator"
deDomainUsers.Password = "foopassword"
Dim primaryGroupToken As Object = Nothing
deRBGroup.Invoke("Add", New Object() {deUser.Path.ToString()})
deRBGroup.CommitChanges()
'Get Primary Group Token of MYGROUP
deRBGroup.Invoke("GetInfoEx", New Object() {New Object() {"primaryGroupToken"}, 0})
primaryGroupToken = deRBGroup.Properties("primaryGroupToken").Value
'Assign Primary Group Token value of MYROUP to the User's PrimaryGroupID
deUser.Properties("primaryGroupID").Value = primaryGroupToken
deUser.CommitChanges()
'Remove the User from "Domain Users" group
deDomainUsers.Invoke("Remove", New Object() {deUser.Path.ToString()})
deDomainUsers.CommitChanges()
Return True
Catch ex As Exception
Return False
End Try
End Function
What is the appropriate way to add a new user to a active directory specific group when the "current user" running the application does not have access rights to add new users?
Run the app as a user that does have those permissions... but you already know this:
I assume the answers is ... to create a user in the Active Directory that has privileges to add users.
Is their any way possible to not hard-code the password for this user?
Good question. One way to do this by setting up a Windows Scheduled Task. You can setup a task to run on demand, with no actual schedule, and to run as any user you want, including your new service account. You will have to put in the password for that user when you setup the task, but only when you first setup the task, and the actual password won't be stored... only the authentication token, which is not transferable. Then your desktop application can trigger the task to start.
Another way to do this is to grant the unprivileged HR or helpdesk users who run your app permissions to create new users just within your specific OU. In the case of a web app, you can also do this for the user account that runs the web site, as long as you have appropriate logging and auditing in place.
The other option is to create a separate service to create the users, which runs as the appropriate user. This could be a web service, where less-privileged authenticated users can post the new account information, or it could be a Windows service doing something like watching a file share, where your unprivileged users then have the ability or write to the file share. Then your program can know how to call the service or write the correct file formats into the share.

HttpContext.Current.User.Identity not populated after sign in

So I'm using AspNet Identity and I'm trying to access the User session variable in Http.Context.Current.User after signing in. I've read online that it should be automatically populated once the sign in attempt is successful. However this doesn't seem to be the case for me.
This is my code:
Dim email As String = txtEmail.Text
Dim password As String = txtPassword.Text
Dim user As ApplicationUser
If Session("LocalNetwork") Then
Await _signInManager.PasswordSignInAsync(email, password, False, False))
Dim y = HttpContext.Current.User.Identity.GetUserId
End If
The signin is successful and I'm trying to access my UsersID but it returns null.
Web config:
<authentication mode="None" />
Anyone know why?
It's because I was checking if the user was authenticated in the same request as updating them. So they wont be authenticated until the end of the request.

DocuSign Embedded RequestRecipientToken - 500 internal Server Error

-Issue Resolved
On Live accounts that Use Embedded Signing, The Account Manager will need to either disable In Session or apply the accounts X.509 Certificate.
There is no way to bypass without the DocuSign Account Managers/Customer Support making updates to non forward facing settings.
-Using SOAP API in a VB.NET application.
I have recently moved our application to live after endless testing on the staging environment. Everything is working as expected except when I get too opening the recipient signature page.
When I make the RequestRecipientToken call I receive the error "One or both of Username and Password are invalid."
The API log give me 00_Internal Server Error_RequestRecipientToken.txt
the log doesn't really give me any info just shows that call.
I know this all works on staging, and I have tried to have all my account settings the same on both environments.
After looking all over I saw that X509 Certificate was recommended, so I added this last line in my DSAPI
-update code:
Protected Overrides Function GetWebRequest(uri As Uri) As WebRequest
IntegratorKey = SettingsHelper.sIntegrationKey
Password = SettingsHelper.sAPIPassword
Username = SettingsHelper.sAPIUserName
Dim r As System.Net.HttpWebRequest = MyBase.GetWebRequest(uri)
r.Headers.Add("X-DocuSign-Authentication", "<DocuSignCredentials><Username>" & Username & "</Username><Password>" & Password & "</Password><IntegratorKey>" & IntegratorKey & "</IntegratorKey></DocuSignCredentials>")
Dim store As X509Store = New X509Store(StoreName.My, StoreLocation.CurrentUser)
store.Open(OpenFlags.ReadOnly)
Dim certs As X509Certificate2Collection = store.Certificates.Find(X509FindType.FindByIssuerDistinguishedName, <{OUR VALUE}>, False)
Dim cert As New X509Certificate2
If certs.Count > 0 Then
cert = certs(0)
Dim securityToken = New X509SecurityToken(cert)
r.ClientCertificates.Add(securityToken.Certificate)
End If
store.Close()
Return r
End Function
This did not help.
Any help would be appreciated.

Google API OAuth2 access with Access and Refresh Tokens .net

I am trying to figure out how to get permanent access to a users Google Calendar with OAuth2. I am at the point that I can get the user to authorize access and I have the AccessToken, RefreshToken, and/or the complete Response Token from Google stored in a database.
The issue I am facing is how to get these tokens in to a credential in the Google API. I have found no examples that work. I have tried a few things. It may be as simple as I am missing a reference to a dll that I cannot figure out. The GoogleCredential.Builder() seems to be the way to go, but I cannot find it anywhere except for the Java API.
Here is the closest I have gotten. The issue is how to create the correct credentials.
Dim user As CRMUser = GetUser(Membership.GetUser().ProviderUserKey)
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(CalendarService.Scope.Calendar)
Dim ClientID As String = System.Configuration.ConfigurationManager.AppSettings("GoogleCalendarApplicationClientID").ToString()
Dim ClientSecret As String = System.Configuration.ConfigurationManager.AppSettings("GoogleCalendarApplicationClientSecret").ToString()
Dim service As CalendarService
Dim credential As GoogleCredential = New GoogleCredential.Builder().setJsonFactory(jsonFactory).setTransport(httpTransport).setClientSecrets(ClientID, ClientSecret).build()
credential.setAccessToken(user.GoogleUserToken)
credential.setRefreshToken(user.GoogleRefreshToken)
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "VB.NET Calendar Sample"
service = New CalendarService(initializer)

VB.NET (WebRequest Authentication Issue)

I'm new to WebRequest authentication and have been researching how to authenticate w/ a couple websites to pull some excel data from them. Couple things I'm confused about is
a.) how to properly read a log from Fiddler (using this to pick up get/post data from the website authentication)
b.) how do use the data from Fiddler to program the VB.NET WebRequest properly.
I've been able to authenticate w/ websites that use simple authentication HTTPS, but any site that does any redirects/REST/cookie auth I'm lost...
Let me know if I can provide anymore detail.
Dim req As Net.HttpWebRequest = Net.WebRequest.Create(Url)
If Not Login = Nothing AndAlso Not Password = Nothing Then
Dim myCache As New System.Net.CredentialCache()
myCache.Add(New Uri(Url), "Basic", New System.Net.NetworkCredential(Login, Password))
req.Credentials = myCache
End If
Dim sr As New StreamReader(req.GetResponse().GetResponseStream())
Dim ss as string = sr.ReadToEnd
'Save it as excel & close stream
sr.Close()