Giter VIP home page Giter VIP logo

omniauth-microsoft_graph's Introduction

Omniauth::MicrosoftGraph ruby workflow

Microsoft Graph OAuth2 Strategy for OmniAuth. Can be used to authenticate with Office365 or other MS services, and get a token for the Microsoft Graph Api, formerly the Office365 Unified Api.

Installation

Add this line to your application's Gemfile:

gem 'omniauth-microsoft_graph'

And then execute:

$ bundle

Or install it yourself as:

$ gem install omniauth-microsoft_graph

Usage

Register a new app in the Azure Portal / App registrations to get the AZURE_APPLICATION_CLIENT_ID and AZURE_APPLICATION_CLIENT_SECRET below.

Configuration

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :microsoft_graph, ENV['AZURE_APPLICATION_CLIENT_ID'], ENV['AZURE_APPLICATION_CLIENT_SECRET']
end

Login Hint

Just add {login_hint: "[email protected]"} to your url generation to form:

/auth/microsoft_graph?login_hint=email@example.com

Domain Verification

Because Microsoft allows users to set vanity emails on their accounts, the value of the user's "email" doesn't establish membership in that domain. Put another way, user [email protected] can edit their email in Active Directory to [email protected], and (depending on your auth implementation) may be able to log in automatically as that user.

To establish membership in the claimed email domain, we use two strategies:

  • email domain matches userPrincipalName domain (which by definition is a verified domain)
  • The user's id_token includes the xms_edov ("Email Domain Ownership Verified") claim, with a truthy value

The xms_edov claim is optional, and must be configured in the Azure console before it's available in the token. Refer to Clerk's guide for instructions on configuring the claim.

If you're not able or don't need to support domain verification, you can bypass for an individual domain:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :microsoft_graph,
           ENV['AZURE_APPLICATION_CLIENT_ID'],
           ENV['AZURE_APPLICATION_CLIENT_SECRET'],
           skip_domain_verification: %w[contoso.com]
end

Or, you can disable domain verification entirely. We strongly recommend that you do not disable domain verification if at all possible.

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :microsoft_graph,
           ENV['AZURE_APPLICATION_CLIENT_ID'],
           ENV['AZURE_APPLICATION_CLIENT_SECRET'],
           skip_domain_verification: true
end

nOAuth: How Microsoft OAuth Misconfiguration Can Lead to Full Account Takeover from Descope

Upgrading to 1.0.0

This version requires OmniAuth v2. If you are using Rails, you will need to include or upgrade omniauth-rails_csrf_protection. If you upgrade and get an error in your logs complaining about "authenticity error" or similiar, make sure to do bundle update omniauth-rails_csrf_protection

Contributing

  1. Fork it ( https://github.com/synth/omniauth-microsoft_graph/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

omniauth-microsoft_graph's People

Contributors

bradgessler avatar dzunk avatar fjaeger avatar jaedonfarrugia avatar jeppeliisberg avatar joelvh avatar mjjar avatar nishidayuya avatar randomor avatar scttdavs avatar synth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

omniauth-microsoft_graph's Issues

Support omniauth 2.0

Is there anything stopping this from being supported by OmniAuth 2.0 and Omniauth-Oauth2 1.0?

Getting OAuth2 Authorization code was already redeemed error

I am getting this error, after upgradering the gem to 0.3.3 and added as a devise omniauth.

I, [2021-03-02T21:35:28.041607 #13350]  INFO -- omniauth: (microsoft_graph) Callback phase initiated.
I, [2021-03-02T21:35:28.812240 #13350]  INFO -- omniauth: (microsoft_graph) Callback phase initiated.
E, [2021-03-02T21:35:29.296444 #13350] ERROR -- omniauth: (microsoft_graph) Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant: AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.

My devise config looks like this

  config.omniauth :microsoft_graph,
                  ENV.fetch('AZURE_APP_ID', nil),
                  ENV.fetch('AZURE_APP_SECRET', nil),
                  scope: ENV.fetch('AZURE_SCOPES', nil),
                  provider_ignores_state: true

Where scopes are the following:
AZURE_SCOPES = "openid profile email offline_access user.read tasks.read calendars.readwrite"

So it should have the refresh token.

devise (4.7.1)    
oauth2 (1.4.4)
omniauth (1.9.1)
omniauth-microsoft_graph (0.3.3)
omniauth-oauth2 (1.7.1)
omniauth-rails_csrf_protection (0.1.2)
rails 6.1.3
ruby 2.6.3

Why isn't he gem handle/use the refresh token? And how can I debug this more?

Missing default login scopes to allow requesting incremental scopes

When attempting to use this strategy with the OmniAuth setup phase, we are unable to login.

The OmniAuth setup phase allows us to incrementally request scopes by using a #setup method in the Sessions controller, for example.

This strategy is failing due to missing the DEFAULT_SCOPES that other OmniAuth strategies have. An example is the Google OAuth2 strategy. They allow passing scopes in the params but fallback to scopes that simply allow login if none were passed.

The fix for this should be something like this but I haven't tested it

DEFAULT_SCOPES = 'openid email profile User.Read'
      def authorize_params
        super.tap do |params|
          %w[display score auth_type].each do |v|
            if request.params[v]
              params[v.to_sym] = request.params[v]
            end
          params[:scope] ||= DEFAULT_SCOPES
          end
        end
      end

Authentication failure invalid_credentials: CSRF detected

Hi,

Im trying to develop an addin for outlook. The addin backend is developed in rails, and I am using the devise_token_auth gem for authentication.
Im using this gem to be able to use oauth and get the user to log in to the application. In my addin, I use a frame to get the /auth/microsoft_graph url and thus start the authentication process.

When I use the addin from the outlook standalone app, authentication runs smoothly and Im able to successfully log in. But if I try to open the addin on outlook for the web i get an CSRF error

Started GET "/auth/microsoft_graph" for 185.227.213.4 at 2021-01-21 12:37:21 +0100
   (0.4ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Started GET "/omniauth/microsoft_graph?resource_class=User" for 185.227.213.4 at 2021-01-21 12:37:21 +0100
I, [2021-01-21T12:37:21.665192 #54893]  INFO -- omniauth: (microsoft_graph) Request phase initiated.
   (0.1ms)  BEGIN
  ActiveRecord::SessionStore::Session Update (0.4ms)  UPDATE "sessions" SET "data" = $1, "updated_at" = $2 WHERE "sessions"."id" = $3  [["data", "BLABLA\n"], ["updated_at", "2021-01-21 11:37:21.695389"], ["id", 4182]]
   (0.7ms)  COMMIT
Started GET "/omniauth/microsoft_graph/callback?code=blabla&state=blabla&session_state=blablabla" for 185.227.213.4 at 2021-01-21 12:37:22 +0100
I, [2021-01-21T12:37:22.041232 #54893]  INFO -- omniauth: (microsoft_graph) Callback phase initiated.
E, [2021-01-21T12:37:22.046415 #54893] ERROR -- omniauth: (microsoft_graph) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
E, [2021-01-21T12:37:22.046462 #54893] ERROR -- omniauth: (microsoft_graph) Authentication failure! invalid_credentials: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
  

I have tried setting provider_ignores_state: true int the omniauth.rb config

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :microsoft_graph, ENV['AZURE_APPLICATION_CLIENT_ID'], ENV['AZURE_APPLICATION_CLIENT_SECRET'],
    provider_ignores_state: true,
    scope: ENV['AZURE_SCOPE']
end 

but that then gives a NotImplementedError (no default_devise_mapping set): error.

Do you have any suggesstion?

Faraday::ConnectionFailed

I'm currently following the Ruby Connect Rest Sample and using this gem to authenticate. I've done the necessary setup, put in the environmental variables, but after it redirects to microsoft and and I give permission to my email to access the application, it never redirects to my app URL and throws this error:

screen shot 2018-05-02 at 1 30 08 pm

Authentication failure (JWT::DecodeError)

Some accounts are failing with this error while other work without any issues:
dummy

ERROR -- omniauth: (microsoft_graph) Authentication Failure! Could not find public key for kid ----------

This 'kid' key doesn't match what I have set for my environment variables

Release 0.1.1 on rubygems?

You should release the latest version on to rubygems, or at least add this to the README:

gem 'omniauth-microsoft_graph', github: 'synth/omniauth-microsoft_graph',
                                                     ref: '5ac8cedcd660ac1ead'

Lost a good bunch of time trying to figure out why I was getting "deprecation" errors :(

example.rb

$ ruby example.rb
.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- omniauth-microsoft_graph (LoadError)
    from .rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from example.rb:2:in `<main>'

I then changed the top of the file to be:

-require 'omniauth-microsoft_graph'
+require 'microsoft_graph'

and it now works ๐Ÿผ

$ ruby example.rb
[2016-06-22 08:03:11] INFO  WEBrick 1.3.1
[2016-06-22 08:03:11] INFO  ruby 2.3.1 (2016-04-26) [x86_64-darwin13]
== Sinatra (v1.4.7) has taken the stage on 4200 for development with backup from WEBrick
[2016-06-22 08:03:11] INFO  WEBrick::HTTPServer#start: pid=6031 port=4200

Refresh token missing from callback data...?

Hi,

I'm using omniauth-microsoft_graph for connecting with Microsoft Graph to import user's contacts. I have no problem signing users in and using the returned token to import data from MS Graph API. However, the callback doesn't return a refresh token for some reason. Here's what it looks like:

{
  "provider":  "...",
  "uid":       "...",
  "info": {
    "email":       "...",
    "first_name":  "...",
    "last_name":   "...",
    "name":        "...",
    "nickname":    "..."
  },
  "credentials": {
    "token":       "...",
    "expires_at":  1597674066,
    "expires":     true
  },
  "extra": {
    "raw_info": {
      "@odata.context":     "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
      "businessPhones":     [],
      "displayName":        "...",
      "givenName":          "...",
      "jobTitle":           null,
      "mail":               "...",
      "mobilePhone":        null,
      "officeLocation":     null,
      "preferredLanguage":  "en-GB",
      "surname":            "...",
      "userPrincipalName":  "...",
      "id":                 "..."
    },
    "params": {
      "token_type":      "Bearer",
      "scope":           "Contacts.Read User.Read profile openid email",
      "ext_expires_in":  3599
    }
  }
}

Because of other gems I can only use version 0.2.1 and I'm wondering if that could be the problem? Or is that unrelated?

Thanks!

This gem clashes with msgraph-sdk-ruby

Adding both gems to Gemfile:

gem 'omniauth-microsoft_graph'

gem 'microsoft_graph'

And then using a rails console:

> MicrosoftGraph
Traceback (most recent call last):
        1: from (irb):1
NameError (uninitialized constant MicrosoftGraph)

This happens (I think) because both gems have a lib/microsoft_graph.rb file, which causes require 'microsoft_graph' to fail.

You can get a similar result with IRB:

Requiring microsoft_graph first โœ”๏ธ

$ irb
2.5.1 :001 > require 'microsoft_graph'
 => true 
2.5.1 :002 > MicrosoftGraph
 => MicrosoftGraph 
2.5.1 :003 > require '/home/nuno/.rvm/gems/ruby-2.5.1/bundler/gems/omniauth-microsoft_graph-5ac8cedcd660/lib/microsoft_graph.rb'
 => true 
2.5.1 :004 > OmniAuth::Strategies::MicrosoftGraph
 => OmniAuth::Strategies::MicrosoftGraph

Requiring omniauth-microsoft_graph first ๐Ÿ’ฅ

$ irb
2.5.1 :001 > require '/home/nuno/.rvm/gems/ruby-2.5.1/bundler/gems/omniauth-microsoft_graph-5ac8cedcd660/lib/microsoft_graph.rb'
 => true 
2.5.1 :002 > OmniAuth::Strategies::MicrosoftGraph
 => OmniAuth::Strategies::MicrosoftGraph
2.5.1 :003 > require 'microsoft_graph'
 => true 
2.5.1 :004 > MicrosoftGraph
Traceback (most recent call last):
        2: from /home/nuno/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>'
        1: from (irb):4
NameError (uninitialized constant MicrosoftGraph)

See:
https://github.com/microsoftgraph/msgraph-sdk-ruby/blob/master/lib/microsoft_graph.rb

Not sure how to solve this, but perhaps having a the prefix: omniauth- in that file would solve it?

Unable to login / microsoft says "reply address" is different but it isn't

I registered an app at microsoft. If I use omniauth-microsoft_graph I always get the following error. I notice, I already added https://me.zammad.com/auth/microsoft_graph/callback as Redirect URLs in https://apps.dev.microsoft.com/#/appList - it seems that microsoft is not accepting the http params ?code=ABC&state=123&session_state=456. Any hint would be wonderful!

invalid_client: AADSTS70002: Error validating credentials.
AADSTS50011: The reply address 'https://me.zammad.com/auth/microsoft_graph/callback?code=ABC&state=123&session_state=456' does not match the reply address 'https://me.zammad.com/auth/microsoft_graph/callback' provided when requesting Authorization code.
Trace ID: a7deb585-be07-40fc-8a63-d78dfd07xxxx
Correlation ID: a1c9b81e-5ac6-4b1a-befb-97b12e37xxxx
Timestamp: 2017-07-13 14:18:36Z
{
  "error":"invalid_client",
  "error_description":"AADSTS70002: Error validating credentials. AADSTS50011: The reply address 'https://me.zammad.com/auth/microsoft_graph/callback?code=ABC&session_state=456' does not match the reply address 'https://me.zammad.com/auth/microsoft_graph/callback' provided when requesting Authorization code.\r\nTrace ID: a7deb585-be07-40fc-8a63-d78dfd07xxxx\r\nCorrelation ID: a1c9b81e-5ac6-4b1a-befb-97b12e37xxxx\r\nTimestamp: 2017-07-13 14:18:36Z",
  "error_codes":[70002,50011],
  "timestamp":"2017-07-13 14:18:36Z",
  "trace_id":"a7deb585-be07-40fc-8a63-d78dfd07xxxx",
  "correlation_id":"a1c9b81e-5ac6-4b1a-befb-97b12e37xxxx"
}

Used gems:

$ bundle show |grep omni
  * omniauth (1.6.1)
  * omniauth-facebook (4.0.0)
  * omniauth-github (1.3.0)
  * omniauth-gitlab (1.0.2)
  * omniauth-google-oauth2 (0.5.0)
  * omniauth-linkedin-oauth2 (0.1.5)
  * omniauth-microsoft_graph (0.1.0)
  * omniauth-oauth (1.1.0)
  * omniauth-oauth2 (1.4.0)
  * omniauth-twitter (1.2.1)

Ruby:

$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]

Email not found

What?

Hi, I'm trying to do Single Sign on but email is not returned if I try request.env['omniauth.auth'].info.email. This is returning nil in my personal hotmail account.
I managed to get the email here:

request.env['omniauth.auth'].extra.raw_info['userPrincipalName']

Do you know why this can be? Could make sense to also find the email there as a fallback?

This are the permissions I have in my Azure application
image

Common endpoint is not supported for single-tenant app registrations

Good morning ๐Ÿ‘‹

I started trying to use this gem this morning to authenticate users within my organisation, during the app registration with Microsoft we select the "Accounts in this organizational directory only (Single tenant)" option.

However, it seems that the endpoints for single-tenant app registrations include the Tenant ID, and don't use the /common URL.

Trying to use this gem provider with a single-tenant app registration results in the following error once directed to Microsoft.

Application 'xxx' is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.

I'm thinking that the Tenant ID should be an optional config variable alongside the Client ID and Client Secret, and if one is provided it should be used in the generation of the authorize_url and token_url, only falling back to /common if one is not provided?

Appreciate any thoughts on this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.