· 1 min read
Screencast: APIs schützen
Downloads in verschiedenen Formaten:
Resourcen:
- Episode 350: REST API Versioning
- HTTP Basic Authentication
- HTTP Token Authentication
- OAuth
- Doorkeeper
- oauth2
- rack-oauth2-server
- oauth2-provider
terminal
[bash] rails g model api_key access_token curl http://localhost:3000/api/products -I curl http://localhost:3000/api/products -u ‘admin:secret’ curl ‘http://localhost:3000/api/products?access\_token=123’ -I curl http://localhost:3000/api/products -H ‘Authorization: Token token=“c576f0136149a2e2d9127b3901015545”’ [/bash]
api/v1/products_controller.rb
[ruby] # http_basic_authenticate_with name: “admin”, password: “secret” before_filter :restrict_access
private
# def restrict_access # api_key = ApiKey.find_by_access_token(params[:access_token]) # head :unauthorized unless api_key # end
def restrict_access authenticate_or_request_with_http_token do |token, options| ApiKey.exists?(access_token: token) end end [/ruby]
models/api_key.rb
[ruby] before_create :generate_access_token
private
def generate_access_token begin self.access_token = SecureRandom.hex end while self.class.exists?(access_token: access_token) end [/ruby]