Search code examples
rubyhttpazure-devopscredentials

Add network credentials in Ruby


I have a question about how the network credentials can be added to a request in Ruby?

I have tried to make a request but it was rejected because it does not have credentials. At the moment I have something like that:

url = URI.parse("http://dev.azure/tfs/#{collection}/#{proyect}/_apis/git/repositories/#{idrepositori}/pullrequest/#{idPR}?api-version=5.0")
puts "  url #{url}"
req = Net::HTTP::Post.new(url, 'Content-Type' => 'application/json') 
res = Net::HTTP.start(url.hostname, url.port) do |http| 
  http.request(req) 
end

Solution

  • I found a solution, using a ntlm / http library

    This must also be exported in the gem file

    ruby "2.6.6"
    source "https://rubygems.org"
    gem "dependabot-omnibus", "~> 0.118.8"
    gem 'ruby-ntlm', '~> 0.0.4'
    

    The ruby code can be worked with the ntlm_auth function

    require 'uri'
    require 'net/http'
    require 'json'
    require 'ntlm/http'
        
    url = URI.parse("http://dev.azure/tfs/#{collection}/#{proyect}/_apis/git/repositories/#{idrepositori}/pullrequest/#{idPR}?api-version=5.0")
        puts "  url #{url}"
        req = Net::HTTP::Post.new(url, 'Content-Type' => 'application/json') 
        req.ntlm_auth('User','Domain', 'Password')
        req.body = {"status": "completed","lastMergeSourceCommit": {"commitId": "123"},"completionOptions":{"deleteSourceBranch":"true"}}.to_json                
        res = Net::HTTP.start(url.hostname, url.port) do |http| 
          http.request(req) 
        end