Home > OS >  Ruby & IMAP - Accessing Office 365 with Oauth 2.0
Ruby & IMAP - Accessing Office 365 with Oauth 2.0

Time:10-30

So MS disabled IMAP for basic auth as we all know.

I am trying to figure out how to get the OAUTH 2.0 working using ruby (not ruby on rails). I have Azure APP and everything needed (I think), but I can not find any code related to ruby and getting the access token.

First step is completed, but next step is to get the access token. https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

I need to read different Outlook mailboxes.

Could someone please explain how to do this?

CodePudding user response:

SOLUTION for me!

Steps I took.

  1. Made an Azure app ('Device Flow' was the easiest way to go for me) Check the Steps in the link. You also need to change some settings in your APP if you want to use IMAP. See the youtube link here between 2:50 - 4:30
  2. Get the postman requests from this link (scroll down a little) (click here)
  3. From postman you can use "Device Flow" requests.
  4. Start with Device Authorization Request (you need a scope and client_id for this) I used https://outlook.office.com/IMAP.AccessAsUser.All scope.
  5. go to the link that you got back from the request and enter the required code.
  6. now go to Device Access Token Request and use the "device_code" from the last request and put that under code, under body.
  7. You should get an access_token

Connect using ruby

require 'gmail_xoauth' # MUST HAVE! otherwise XOAUTH2 auth wont work
require 'net/imap'
    imap = Net::IMAP.new(HOST, PORT, true)
    access_token = "XXXXX"
    user_name = "[email protected]"
    p imap.authenticate('XOAUTH2',"#{user_name}", "#{access_token}")

    # example
    imap.list('','*').each do |folders|
      p folders
    end

XOAUTH2 Returns

#<struct Net::IMAP::TaggedResponse tag="RUBY0001", name="OK", data=#<struct Net::IMAP::ResponseText code=nil, text="AUTHENTICATE completed.">, raw_data="RUBY0001 OK AUTHENTICATE completed.\r\n

Just to specify

HOST = 'outlook.office365.com'
PORT = 993
  • Related