1
votes

I have created a Ruby App to send email using Microsoft Graph API. I get access token without a user based on : https://docs.microsoft.com/en-us/graph/auth-v2-service#5-use-the-access-token-to-call-microsoft-graph

url = URI.parse("https://login.microsoftonline.com/common/oauth2/v2.0/token")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")

req = Net::HTTP::Post.new(url.request_uri)
req.set_form_data({
    'client_id' => CLIENT_ID, 
    'client_secret' => CLIENT_SCERET,
    'grant_type' => 'client_credentials',
    'scope' => 'https://graph.microsoft.com/.default'
})
response = http.request(req)

I got token.

Next, I want send mail to any user with my application on portal azure, which have api permissions for it.

enter image description here

Then, I call send_mail function.

url = URI.parse("https://graph.microsoft.com/v1.0/users/{MYID}/sendMail")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
req = Net::HTTP::Post.new(url.request_uri)
req["Authorization"] = "Bearer #{get_token_without_user}"
req["Content-type"] = "application/json"

req.set_form_data({
    "message": {
       "subject": "Meet for lunch?",
       "body": {
          "contentType": "Text",
          "content": "The new cafeteria is open."
        }
     },
     "toRecipients": [
        {
          "emailAddress": {
             "address": "[email protected]"
          }
     }],
     "saveToSentItems": "false"
})
response = http.request(req)

I receive this error :

enter image description here

So, can anybody guide me where is my mistake ? Thanks so much!

1
I think you have to check Microsoft's API for this.Vatsal Jain
@VatsalJain I updated more source to get token. Is it ok ?Ryan Tran
v2.0 is missing in the url and try adding the header for Content-TypeVatsal Jain
Sorry, it still does not working. :(Ryan Tran
It would help to see the source code that makes the actual call to the graph endpoint. Perhaps there is something wrong with the request and not the token...Paul Schaeflein

1 Answers

0
votes

I don't know Ruby -- is the scope parameter URLEncoded when sent over the wire?

Grab the response and have a look. Does it have an access_token property? If so, copy the value of that property and paste it in https://jwt.ms. Look for the scopes or roles in the decoded token - it should match what has been setup in the AAD portal.