`

oauth github和multiple oauth

 
阅读更多

http://railscasts.com/episodes/241-simple-omniauth

OmniAuth is a recently released library from Intridea that gives you drop-in Rack middleware to authenticate with just about anything. In this guest post we’re going to walk you through how to use OmniAuth and Rails 3 to allow multiple-provider authentication in your app.

Enter OmniAuth
The first step is to add OmniAuth to your Gemfile:

gem 'omniauth'

Now we need to create an initializer to make use of the OmniAuth middleware. Easy enough, in config/intitializers/omniauth.rb add:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'
  provider :facebook, 'APP_ID', 'APP_SECRET'
  provider :linked_in, 'CONSUMER_KEY', 'CONSUMER_SECRET'
end

You’ve actually already done quite a lot. Try running your application with rails server and navigating to /auth/twitter, /auth/facebook, or /auth/linkedin. You should (assuming you’ve set up applications with the respective providers correctly) be redirected to the appropriate site and asked to login.

Handling the Callback
Upon confirmation, you should be redirected back and get a routing error from Rails from /auth/yourprovider/callback. So let’s add a route! In
#config/routes.rb add:Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'
  provider :facebook, 'APP_ID', 'APP_SECRET'
  provider :linked_in, 'CONSUMER_KEY', 'CONSUMER_SECRET'
end


match '/auth/:provider/callback', :to =》 'sessions#create'

But of course, this points to a non-existent controller, so let’s create that as well:

rails g controller sessions
Now in our sessions_controller.rb lets add a bit of code:

class SessionsController  request.env['rack.auth'].inspect
  end
end

If you start up the app again and go through the auth process, you should now see a hash that includes a whole lot of information about the user instead of a routing error. We’re on our way!

Authorizations and Users
One of the nice things about OmniAuth is that it doesn’t assume how you want to handle the authentication information, it just goes through the hard parts for you. We want users to be able to log in using one or many external services, so we’re actually going to separate users from authorizations. Let’s create simple Authorization and User models now.

rails g model authorization provider:string uid:string user_id:integer
rails g model user name:string

This creates the models we need with appropriate migrations. Notice that the User model doesn’t need to contain any information about authentication providers because we’ll model that through a relationship to the Authorization model. Set up your models like so:

class User  :provider
end

Here we’re modeling very simple relationships and making sure that the Authorization has both a provider (e.g. “twitter” or “facebook”) and a uid (i.e. the external service ID). Next up, we’ll wire these models into our controller to create a real sign in process.

Signing Up/In
One of the nice things about external authentication is you can collapse the sign up and sign in process into a single step. What we’ll do here is:

  1. When a user signs in, look for existing Authorizations for that external account.
  2. Create a user if no authorization is found.
  3. Add an authorization to an existing user if the user is already logged in.


Let’s work backwards for this functionality by adding the code we want to have to the controller. Modify the create action in SessionsController to look like this:

def create
  auth = request.env['rack.auth']
  unless @auth = Authorization.find_from_hash(auth)
    # Create a new user or add an auth to existing user, depending on
    # whether there is already a user signed in.
    @auth = Authorization.create_from_hash(auth, current_user)
  end
  # Log the authorizing user in.
  self.current_user = @auth.user

  render :text => "Welcome, #{current_user.name}";
end

Now let’s implement some of these methods. First up, adding some class methods to Authorization:

# in authorization.rb

def self.find_from_hash(hash)
  find_by_provider_and_uid(hash['provider'], hash['uid'])
end

def self.create_from_hash(hash, user = nil)
  user ||= User.create_from_hash!(hash)
  Authorization.create(:user => user, :uid => hash['uid'], :provider => hash['provider'])
end

Now we need to add the method referenced above to the User class:

# in user.rb

def self.create_from_hash!(hash)
  create(:name => hash['user_info']['name'])
end

Finally, we need to add some helpers to ApplicationController to handle user state:

class ApplicationController 

Voila! Now a user can sign in using any of their accounts and a User will automatically be fetched or created. This is merely a small jumping off point, but from here it would be trivial to do any of the following:

  • Show the user a list of services that they’re connected to and let them connect to additional ones (creating Authorizations) or delete existing connections.
  • Provide a sign out (just delete the :user_id from the session.)
  • Connect to APIs of the authenticating services (add token and secret to Authorization, and store them from the auth key of the rack.auth hash).


We hope that you’ll consider dropping OmniAuth into your Rails Rumble application (it also works really easily with Sinatra) and this post has given you a good foundation for fast and easy multi-provider authentication in Rails 3 with OmniAuth.

分享到:
评论

相关推荐

    electron-oauth-github:使用Web应用程序流程策略向Github授予OAuth授权的电子助手

    Electron OAuth Github软件包。 如何使用它 ? 该软件包可帮助获得来自Github的OAuth授权。 它使用此处描述的web application flow : : 包提供2个功能: module.exports = { getAuthorizationCode, ...

    Gerrit.jar Github OAuth2.0 源码

    而OAuth2.0是一种授权框架,广泛用于安全地访问Web服务,例如GitHub。在本项目中,我们关注的是如何将Gerrit与GitHub集成,并利用OAuth2.0进行身份验证。 首先,让我们深入了解Gerrit的OAuth2.0支持。在Gerrit 2.11...

    nextjs-oauth-github:通过NextAuth登录GitHub

    nextjs-oauth-github 通过NextAuth登录GitHub

    django-github-oauth:Github OAuth 的身份验证后端

    Django Github OAuth 使用 Github 的 OAuth 对 Django Web 应用程序中的用户进行身份验证的后端。安装通过设置工具 python setup.py install通过 PyPi pip install django-github-oauth用法在您的project/settings....

    spring-oauth2-github:将Spring Boot与oauth2结合使用的演示

    spring-oauth2-github 将Spring Boot与oauth2结合使用的演示目录入门要求 :spouting_whale:用法在开发模式下运行应用服务器: $ docker-compose up -d 停止开发应用服务器: $ docker-compose stop todos贡献错误,...

    spring-boot集成spring-security的oauth2实现github登录网站的示例

    Spring Boot 集成 Spring Security 的 OAuth2 实现 GitHub 登录网站的示例 本篇文章主要介绍了 Spring Boot 集成 Spring Security 的 OAuth2 实现 GitHub 登录网站的示例,非常具有实用价值,需要的朋友可以参考下...

    oauth2github

    OAuth2 是一个授权框架,广泛应用于各种Web应用和API服务,包括GitHub。在这个场景中,我们探讨的是如何将你的应用程序与GitHub的OAuth2服务集成,以便用户可以通过他们的GitHub账户安全地登录你的应用。 首先,...

    Github第三方(OAuth2.0)登录

    其中,GitHub作为全球知名的代码托管平台,提供了基于OAuth2.0协议的第三方登录服务。OAuth2.0是一个授权框架,允许应用在不获取用户密码的情况下获取有限的访问权限。 **OAuth2.0简介** OAuth2.0是一种广泛采用的...

    java Web第三方登录实现(基于OAuth2.0,包含Github和QQ登录,附源码)完整源码

    本项目是基于OAuth2.0协议实现的第三方登录功能,包括GitHub和QQ的登录接口集成,同时也附带了完整的源代码。 OAuth2.0是一个授权框架,它允许第三方应用在用户的授权下获取其在特定服务上的部分数据,但不会暴露...

    twitter+github oauth认证php版

    由于项目需要,同事要做twitter和github的第三方登陆,也就是oauth 认证, 受他委托,我特意给他写了这个实例, 代码可直接运行, 仅供参考。需要的拿走

    verdaccio-github-oauth-ui:Ver用于Verdaccio的GitHub OAuth插件

    这是一个Verdaccio插件,为浏览器和命令行提供GitHub OAuth集成。 产品特点 UI集成,具有完整的登录和注销功能。 单击登录按钮后,用户将重定向到GitHub并返回工作会话。 更新了使用情况信息和适用于安装命令的...

    springboot整合Oauth2,GateWay实现网关登录授权验证

    SpringBoot整合OAuth2和Gateway实现网关登录授权验证是一个复杂而关键的过程,它涉及到现代微服务架构中的安全性设计。OAuth2是一种授权框架,用于保护API并允许第三方应用访问受保护的资源,而Spring Gateway作为...

    springcloud整合oauth2和jwt

    而OAuth2和JWT(JSON Web Token)是两种广泛用于身份验证和授权的技术。本篇文章将深入探讨如何在Spring Cloud项目中整合OAuth2和JWT,以及与MyBatis的集成。 首先,OAuth2是一个开放标准,主要用于授权。它允许第...

    Shiro集成OAuth2

    Apache Shiro是一个强大的Java安全框架,它提供了身份验证、授权、会话管理和加密等功能,而OAuth2则是一种开放标准,用于授权第三方应用访问用户资源。将Shiro与OAuth2集成,可以实现更灵活的安全控制,特别是在...

    Python-Authlib是一个实现OAuth1OAuth2身份验证的客户端和服务端

    2. **OAuth 2**: OAuth 2 更加简单,常用于Google、Facebook、GitHub等平台的API授权。它主要关注的是授权而不是认证,允许用户授权第三方应用访问他们存储在特定服务上的数据,而无需共享他们的登录凭据。OAuth 2的...

    OAuth Server和OAuth Client(JAVA实现,eclipse环境)

    资源为在eclipse开发环境中使用Java搭建OAuth Server和OAuth Client 参考代码为http://code.google.com/p/oauth/ OAuth Server为遵守OAuth 1.0协议的OAuth认证服务器 OAuth Client分为Desktop版本和Webapp版本

    jmeter 实现oauth1.0授权认证

    请注意,由于OAuth 1.0的安全性要求,每次请求的nonce和timestamp都必须是唯一的,因此在实际操作中,nonce和timestamp的生成应在每次请求时动态进行。 总结来说,实现JMeter中的OAuth 1.0认证需要对OAuth协议有...

    Spring security oauth源码

    Spring Security OAuth 是一个用于保护RESTful Web服务的框架,它为OAuth 1.0a和OAuth 2.0协议提供了全面的支持。在这个源码中,我们可能会看到如何将Spring Security与OAuth结合,以构建安全的Web应用程序和服务。...

    Java的oauth2.0 服务端与客户端的实现 (完整源码、demo)

    下载项目压缩包,解压,里面两个maven项目:oauthserver和oauthclient01,分别对应oauth服务端和客户端。 服务端对应的数据库sql文件在源码压缩包里可以看到。 两个项目分别用8082端口(服务端端口)和8081端口...

Global site tag (gtag.js) - Google Analytics