以下2つの記事を参考に、Railsでのユーザ認証機能を追加しています。
参考にしている記事
https://auth0.com/blog/building-secure-apis-with-rails-6-and-auth0/
#環境
Mac
Rails 6.0.4
#やりたいこと
curlコマンドで、headerにtokenを載せてPOSTリクエストを実行して認証を通したい。
記事では以下の部分でやっていることです。
https://auth0.com/blog/building-secure-apis-with-rails-6-and-auth0/#Create-Authorization-Handlers#Test-it-out
コードはこちらです。
$ curl -H "Content-Type: application/json" -H "Authorization: bearer [ACCESS_TOKEN]" -d '{"title":"タイトル1", "content":"説明1"}' -X POST http://localhost:3000/api/v1/articles
[ACCESS_TOKEN]の部分に以下の部分のToken情報をコピペして使っています。
[ACCESS_TOKEN]の部分には、[]や""を使わずに、貼り付けしています。
#エラー内容
コンソール
Uncaught (in promise) Error: Request failed with status code 401 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)
ログ
Started POST "/api/v1/articles" for ::1 at 2021-08-15 09:00:47 +0900 (1.1ms) SELECT sqlite_version(*) (1.3ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC Processing by Api::V1::ArticlesController#create as */* Parameters: {"title"=>"タイトル1", "content"=>"説明1"} Filter chain halted as :authorize_request rendered or redirected Completed 401 Unauthorized in 681ms (Views: 0.5ms | ActiveRecord: 0.0ms | Allocations: 5725)
401エラーなので、認証エラーだというところまでは理解しています。ですが、Token情報はコピペしているので、なぜ認証エラーが出ているのかがわからない状態です。
#やったこと
byebugを使って、気になる部分をデバッグしてみました。
そして気になる部分が
json_web_token.rb
1# app/lib/json_web_token.rb 2require 'net/http' 3require 'uri' 4 5class JsonWebToken 6 def self.verify(token) 7 JWT.decode(token, nil, 8 true, # Verify the signature of this token 9 algorithm: 'RS256', 10 iss: ENV['AUTH0_DOMAIN'], 11 verify_iss: true, 12 aud: ENV['AUTH0_IDENTIFIER'], 13 verify_aud: true) do |header| 14 jwks_hash[header['kid']] 15 end 16 end 17 18 def self.jwks_hash 19 byebug // ここにbyebug 20 jwks_raw = Net::HTTP.get URI("#{ENV['AUTH0_DOMAIN']}/.well-known/jwks.json") // jwks_rawがnilになる 21 jwks_keys = Array(JSON.parse(jwks_raw)['keys']) 22 Hash[ 23 jwks_keys 24 .map do |k| 25 [ 26 k['kid'], 27 OpenSSL::X509::Certificate.new( 28 Base64.decode64(k['x5c'].first) 29 ).public_key 30 ] 31 end 32 ] 33 end 34end
jwks_raw
がnil
になっていることが問題なのかな...?といった感じです。
ENV['AUTH0_DOMAIN']
はrails c
でもきちんと表示されます。
また、https://XXXXXXX.auth0.com/.well-known/jwks.json
にアクセスするとキチンとJSONは表示されるます。
#コード
実際のコードです。
app/lib/json_web_token.rb
# app/lib/json_web_token.rb require 'net/http' require 'uri' class JsonWebToken def self.verify(token) JWT.decode(token, nil, true, # Verify the signature of this token algorithm: 'RS256', iss: ENV['AUTH0_DOMAIN'], verify_iss: true, aud: ENV['AUTH0_IDENTIFIER'], verify_aud: true) do |header| jwks_hash[header['kid']] end end def self.jwks_hash byebug jwks_raw = Net::HTTP.get URI("#{ENV['AUTH0_DOMAIN']}/.well-known/jwks.json") jwks_keys = Array(JSON.parse(jwks_raw)['keys']) Hash[ jwks_keys .map do |k| [ k['kid'], OpenSSL::X509::Certificate.new( Base64.decode64(k['x5c'].first) ).public_key ] end ] end end
app/controllers/secured_controller.rb
ruby
1class SecuredController < ApplicationController 2 before_action :authorize_request 3 4 private 5 6 def authorize_request 7 AuthorizationService.new(request.headers).authenticate_request! 8 rescue JWT::VerificationError, JWT::DecodeError 9 render json: { errors: ['Not Authenticated'] }, status: :unauthorized 10 end 11end
app/services/authorization_service.rb
class AuthorizationService def initialize(headers = {}) @headers = headers end def authenticate_request! verify_token end private def http_token if @headers['Authorization'].present? @headers['Authorization'].split(' ').last end end def verify_token JsonWebToken.verify(http_token) end end
app/controllers/api/v1/articles_controller.rb
module Api module V1 class ArticlesController < SecuredController skip_before_action :authorize_request, only: [:index, :show] before_action :params_name, only: [:show] def index articles = Article.all users = User.all render json: { data: { articles: articles, users: users } }, status: :ok end def show user = @user article = @user.articles.find_by(title: params[:title]) render json: { user: user, article: article }, status: :ok end def create article = Article.create!(article_params) render json: article, status: :created end def destroy article = Article.find(params[:id]) article.delete head :no_content end private def article_params params.permit(:title, :content) end def params_name @user = User.find_by(name: params[:user_name]) end end end end
app/controllers/api/v1/users_controller.rb
module Api module V1 class UsersController < ApplicationController def show user = User.find_by(id: params[:id]) articles = Article.where(user_id: user.id) render json: { user: user, articles: articles }, status: :ok end end end end
app/config/initializers/wrap_parameters.rb
ActiveSupport.on_load(:action_controller) do wrap_parameters format: [] end
app/config/routes.eb
Rails.application.routes.draw do namespace :api do namespace :v1 do root to: "articles#index" get "articles/new", to: "articles#new" resources :articles, only: [:create, :edit, :update, :destory] resources :users, path: "/", param: :name, only: [:show, :create] do get "articles/:id", to: "articles#show" end end end end
Gemfile
記事にしたがって
gem 'dotenv-rails'
gem 'jwt'
gem 'rack-cors'
の3つを追加しました。
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.7.0' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' gem 'rails', '~> 6.0.4' # Use sqlite3 as the database for Active Record gem 'sqlite3', '~> 1.4' # Use Puma as the app server gem 'puma', '~> 4.1' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder # gem 'jbuilder', '~> 2.7' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use Active Model has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Active Storage variant # gem 'image_processing', '~> 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible gem 'rack-cors' gem 'jwt' // 追加した部分です group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do gem 'listen', '~> 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' gem 'dotenv-rails' // 追加した部分です end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
不足している内容などありましたら、なんでもおっしゃってください。まる2日費やしたのですが、わからなかったので質問させていただきました。
どうぞよろしくお願いいたします。????♀️

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。