All Projects → scrogson → Oauth2

scrogson / Oauth2

Licence: mit
An Elixir OAuth 2.0 Client Library

Programming Languages

elixir
2628 projects

Projects that are alternatives of or similar to Oauth2

Rest Api With Lumen
Rest API boilerplate for Lumen micro-framework.
Stars: ✭ 464 (-24.8%)
Mutual labels:  oauth2
Aspnet.security.openidconnect.server
OpenID Connect/OAuth2 server framework for OWIN/Katana and ASP.NET Core
Stars: ✭ 544 (-11.83%)
Mutual labels:  oauth2
Lumen Passport
Making Laravel Passport work with Lumen
Stars: ✭ 585 (-5.19%)
Mutual labels:  oauth2
Spring Cloud Security
Security concerns for distributed applications implemented in Spring
Stars: ✭ 488 (-20.91%)
Mutual labels:  oauth2
Sns auth
通用第三方登录SDK,支持微信,微信扫码,QQ,微博登录,支付宝登录,Facebook,Line,Twitter,Google
Stars: ✭ 520 (-15.72%)
Mutual labels:  oauth2
Books Recommendation
程序员进阶书籍(视频),持续更新(Programmer Books)
Stars: ✭ 558 (-9.56%)
Mutual labels:  oauth2
Auth
:atom: Social (OAuth1\OAuth2\OpenID\OpenIDConnect) sign with PHP
Stars: ✭ 457 (-25.93%)
Mutual labels:  oauth2
Heimdallr.swift
Easy to use OAuth 2 library for iOS, written in Swift.
Stars: ✭ 605 (-1.94%)
Mutual labels:  oauth2
Doorkeeper
Doorkeeper is an OAuth 2 provider for Ruby on Rails / Grape.
Stars: ✭ 4,917 (+696.92%)
Mutual labels:  oauth2
Angular Auth Oidc Client
npm package for OpenID Connect, OAuth Code Flow with PKCE, Refresh tokens, Implicit Flow
Stars: ✭ 577 (-6.48%)
Mutual labels:  oauth2
Example Oauth2 Server
Example for OAuth 2 Server for Authlib.
Stars: ✭ 499 (-19.12%)
Mutual labels:  oauth2
Auth0 Spa Js
Auth0 authentication for Single Page Applications (SPA) with PKCE
Stars: ✭ 507 (-17.83%)
Mutual labels:  oauth2
Identityserver4.samples
Samples for IdentityServer4,use .net core 2.0
Stars: ✭ 561 (-9.08%)
Mutual labels:  oauth2
Cloudfront Auth
An AWS CloudFront [email protected] function to authenticate requests using Google Apps, Microsoft, Auth0, OKTA, and GitHub login
Stars: ✭ 471 (-23.66%)
Mutual labels:  oauth2
Scribejava
Simple OAuth library for Java
Stars: ✭ 5,223 (+746.52%)
Mutual labels:  oauth2
Api Boot
“ ApiBoot”是为接口服务而生的,基于“ SpringBoot”完成扩展和自动配置,内部封装了一系列的开箱即用Starters。
Stars: ✭ 460 (-25.45%)
Mutual labels:  oauth2
Taroco
整合Nacos、Spring Cloud Alibaba,提供了一系列starter组件, 同时提供服务治理、服务监控、OAuth2权限认证,支持服务降级/熔断、服务权重,前端采用vue+elementUI+webpack,可以很好的解决转向Spring Cloud的一系列问题。
Stars: ✭ 545 (-11.67%)
Mutual labels:  oauth2
Easyweb Jwt
基于 SpringBoot、jwt和JwtPermission实现的前后端分离开发框架,接口遵循RESTful风格。
Stars: ✭ 614 (-0.49%)
Mutual labels:  oauth2
Angular Oauth2
AngularJS OAuth2
Stars: ✭ 601 (-2.59%)
Mutual labels:  oauth2
Serverless Authentication Boilerplate
Generic authentication boilerplate for Serverless framework
Stars: ✭ 563 (-8.75%)
Mutual labels:  oauth2

OAuth2 (Client)

An Elixir OAuth2 Client

Build Status Coverage Status

Install

# mix.exs

def application do
  # Add the application to your list of applications.
  # This will ensure that it will be included in a release.
  [applications: [:logger, :oauth2]]
end

defp deps do
  # Add the dependency
  [{:oauth2, "~> 2.0"}]
end

Configure a serializer

This library can be configured to handle encoding and decoding requests and responses automatically based on the accept and/or content-type headers.

If you need to handle various MIME types, you can simply register serializers like so:

OAuth2.Client.put_serializer(client, "application/vnd.api+json", Jason)
OAuth2.Client.put_serializer(client, "application/xml", MyApp.Parsers.XML)

The modules are expected to export encode!/1 and decode!/1.

defmodule MyApp.Parsers.XML do
  def encode!(data), do: # ...
  def decode!(binary), do: # ...
end

Please see the documentation for OAuth2.Serializer for more details.

Debug mode

Sometimes it's handy to see what's coming back from the response when getting a token. You can configure OAuth2 to output the response like so:

config :oauth2, debug: true

Usage

Current implemented strategies:

  • Authorization Code
  • Password
  • Client Credentials

Authorization Code Flow (AuthCode Strategy)

# Initialize a client with client_id, client_secret, site, and redirect_uri.
# The strategy option is optional as it defaults to `OAuth2.Strategy.AuthCode`.

client = OAuth2.Client.new([
  strategy: OAuth2.Strategy.AuthCode, #default
  client_id: "client_id",
  client_secret: "abc123",
  site: "https://auth.example.com",
  redirect_uri: "https://example.com/auth/callback"
])

# Generate the authorization URL and redirect the user to the provider.
OAuth2.Client.authorize_url!(client)
# => "https://auth.example.com/oauth/authorize?client_id=client_id&redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fcallback&response_type=code"

# Use the authorization code returned from the provider to obtain an access token.
client = OAuth2.Client.get_token!(client, code: "someauthcode")

# Use the access token to make a request for resources
resource = OAuth2.Client.get!(client, "/api/resource").body

Client Credentials Flow

Getting an initial access token:

# Initializing a client with the strategy `OAuth2.Strategy.ClientCredentials`

client = OAuth2.Client.new([
  strategy: OAuth2.Strategy.ClientCredentials,
  client_id: "client_id",
  client_secret: "abc123",
  site: "https://auth.example.com"
])

# Request a token from with the newly created client
# Token will be stored inside the `%OAuth2.Client{}` struct (client.token)
client = OAuth2.Client.get_token!(client)

# client.token contains the `%OAuth2.AccessToken{}` struct

# raw access token
access_token = client.token.access_token

Refreshing an access token:

# raw refresh token - use a client with `OAuth2.Strategy.Refresh` for refreshing the token
refresh_token = client.token.refresh_token

refresh_client = OAuth2.Client.new([
  strategy: OAuth2.Strategy.Refresh,
  client_id: "client_id",
  client_secret: "abc123",
  site: "https://auth.example.com",
  params: %{"refresh_token" => refresh_token}
])

# refresh_client.token contains the `%OAuth2.AccessToken{}` struct again
refresh_client = OAuth2.Client.get_token!(refresh_client)

Write Your Own Strategy

Here's an example strategy for GitHub:

defmodule GitHub do
  use OAuth2.Strategy

  # Public API

  def client do
    OAuth2.Client.new([
      strategy: __MODULE__,
      client_id: System.get_env("GITHUB_CLIENT_ID"),
      client_secret: System.get_env("GITHUB_CLIENT_SECRET"),
      redirect_uri: "http://myapp.com/auth/callback",
      site: "https://api.github.com",
      authorize_url: "https://github.com/login/oauth/authorize",
      token_url: "https://github.com/login/oauth/access_token"
    ])
    |> OAuth2.Client.put_serializer("application/json", Jason)
  end

  def authorize_url! do
    OAuth2.Client.authorize_url!(client(), scope: "user,public_repo")
  end

  # you can pass options to the underlying http library via `opts` parameter
  def get_token!(params \\ [], headers \\ [], opts \\ []) do
    OAuth2.Client.get_token!(client(), params, headers, opts)
  end

  # Strategy Callbacks

  def authorize_url(client, params) do
    OAuth2.Strategy.AuthCode.authorize_url(client, params)
  end

  def get_token(client, params, headers) do
    client
    |> put_header("accept", "application/json")
    |> OAuth2.Strategy.AuthCode.get_token(params, headers)
  end
end

Here's how you'd use the example GitHub strategy:

Generate the authorize URL and redirect the client for authorization.

GitHub.authorize_url!

Capture the code in your callback route on your server and use it to obtain an access token.

client = GitHub.get_token!(code: code)

Use the access token to access desired resources.

user = OAuth2.Client.get!(client, "/user").body

# Or
case OAuth2.Client.get(client, "/user") do
  {:ok, %OAuth2.Response{body: user}} ->
    user
  {:error, %OAuth2.Response{status_code: 401, body: body}} ->
    Logger.error("Unauthorized token")
  {:error, %OAuth2.Error{reason: reason}} ->
    Logger.error("Error: #{inspect reason}")
end

Examples

License

The MIT License (MIT)

Copyright (c) 2015 Sonny Scroggin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].