Search code examples
oauth-2.0microsoft-graph-apiomniauth

Microsoft Graph Oauth2 - Getting: "401 - Unauthorized: Access is denied due to invalid credentials"


I'm getting this error when I try to sign in using a microsoft account to my web application:

{
  "error": {
    "code": "UnknownError",
    "message": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\r\n<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>\r\n<style type=\"text/css\">\r\n<!--\r\nbody{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}\r\nfieldset{padding:0 15px 10px 15px;} \r\nh1{font-size:2.4em;margin:0;color:#FFF;}\r\nh2{font-size:1.7em;margin:0;color:#CC0000;} \r\nh3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} \r\n#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:\"trebuchet MS\", Verdana, sans-serif;color:#FFF;\r\nbackground-color:#555555;}\r\n#content{margin:0 0 0 2%;position:relative;}\r\n.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}\r\n-->\r\n</style>\r\n</head>\r\n<body>\r\n<div id=\"header\"><h1>Server Error</h1></div>\r\n<div id=\"content\">\r\n <div class=\"content-container\"><fieldset>\r\n  <h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>\r\n  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>\r\n </fieldset></div>\r\n</div>\r\n</body>\r\n</html>\r\n",
    "innerError": {
      "request-id": "caee116c-483e-4d88-814a-721ce92c6b74",
      "date": "2018-08-10T19:18:47"
    }
  }
}

The app is configured in https://apps.dev.microsoft.com as follows:

  • App with generated password
  • Allow Implicit Flow checked
  • redirect_uri: http://localhost:3000/users/auth/microsoft_graph_oauth2/callback
  • delegated permissions: email, Mail.Read, Mail.Send, offline_access, openid, profile

And the (rails) app is configured with the gems devise and omniauth. This is the omniauth strategy config:

  config.omniauth :microsoft_graph_oauth2,
                  Rails.application.credentials.dig(:oauth, :o365_id),
                  Rails.application.credentials.dig(:oauth, :o365_secret),
                  scope: %w[
                    email profile openid offline_access
                    Mail.Read Mail.Send
                  ].join(' ')

This is the omniauth strategy definition:

module OmniAuth
  module Strategies
    class MicrosoftGraphOauth2 < OmniAuth::Strategies::OAuth2
      option :name, :microsoft_graph_oauth2

      option :client_options, site: 'https://login.microsoftonline.com',
                              token_url: '/common/oauth2/v2.0/token',
                              authorize_url: '/common/oauth2/v2.0/authorize'

      option :authorize_options, %i[
        display score auth_type
        scope prompt
        login_hint domain_hint
        response_mode
      ]

      uid { raw_info['id'] }

      info do
        {
          email:      raw_info['mail'] || raw_info['userPrincipalName'],
          first_name: raw_info['givenName'],
          last_name:  raw_info['surname'],
          name:       full_name,
          nickname:   raw_info['userPrincipalName']
        }
      end

      extra do
        {
          'raw_info' => raw_info,
          'params' => access_token.params
        }
      end

      def callback_url
        options[:redirect_uri] || (full_host + script_name + callback_path)
      end

      def raw_info
        @raw_info ||= access_token.get(
          'https://graph.microsoft.com/v1.0/me'
        ).parsed
      end

      def authorize_params
        super.tap do |params|
          %w[display score auth_type].each do |v|
            next unless request.params[v]
            params[v.to_sym] = request.params[v]
          end
        end
      end

      def full_name
        raw_info['displayName'].presence ||
          raw_info.values_at('givenName', 'surname').compact.join(' ')
      end
    end
  end
end

What am I missing? I cannot find the cause of this error anywhere. Seems that it's some config issue on the Microsoft app definition, but idk what...


Solution

  • Solved after updating the delegated permissions. email, profile are "legacy" (office365 v2 API) permissions, and should be replaced with User.Read to properly authenticate with graph (v1) API