Search code examples
ruby-on-railspowerbioffice365-restapi

How to get access token for creating dataset in Power BI through REST API from Rails APP


Currently I have only client_id and client_secret ,what other parameter do I need for creating dataset


Solution

  • I finally got this. First of all we have to connect our Azure AD and power BI application.

    def index
      update_token
      if session['access_token']
    
      redirect_to YOUR_ACTION
      else
        client = get_client
        a = client.auth_code.authorize_url(:client_id => CLIENT_ID, :resource => RESOURCE_ID, :redirect_uri => REDIRECT_URI)
        redirect_to(a) 
      end
    end
    
    def callback
      begin
        @code = params[:code]
        client = get_client
        token = client.auth_code.get_token(@code, :redirect_uri => REDIRECT_URI, )
        session['access_token'] = token.token
        if token.token.present?
         YOUR_ACTION
        end
      end
    end
    
    def update_token
      token = session['access_token']
      refresh_token = session['refresh_token']
    
      expire_at = session['expire_at']
      @access_token = OAuth2::AccessToken.from_hash(get_client, { :access_token => token, :refresh_token =>  refresh_token, :expire_at => expire_at, :header_format => 'Bearer %s' } )
    
      if @access_token.expired?
    
       @access_token = @access_token.refresh!;
       session['access_token'] = @access_token.token
       session['refresh_token'] = @access_token.refresh_token
       session['expire_at'] = @access_token.expire_at  
       session['instance_url']  = @access_token.params['instance_url']
      end
    end
    
    def get_client
      client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, :site => AUTHORITY, :authorize_url =>  AUTHORIZE_URL, :token_url => TOKEN_URL )
      client
    end
    
    def azure
      callback
    end