質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Authentication

Authentication(認証)は正当性を認証する為の工程です。ログイン処理等で使われます。

Q&A

1回答

2369閲覧

Auth0を使った認証で、ユーザ認証ができず401エラーがでる

yamamotosyo

総合スコア7

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Authentication

Authentication(認証)は正当性を認証する為の工程です。ログイン処理等で使われます。

0グッド

0クリップ

投稿2021/08/15 00:18

以下2つの記事を参考に、Railsでのユーザ認証機能を追加しています。

参考にしている記事
https://auth0.com/blog/building-secure-apis-with-rails-6-and-auth0/

https://qiita.com/pon0204/items/4de8c4b55b348a4c0781#rails-%E3%82%A2%E3%83%97%E3%83%AA%E8%A8%AD%E5%AE%9A-%E9%80%9A%E4%BF%A1%E7%A2%BA%E8%AA%8D

#環境
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

https://qiita.com/pon0204/items/4de8c4b55b348a4c0781#rails-%E3%82%A2%E3%83%97%E3%83%AA%E8%A8%AD%E5%AE%9A-%E9%80%9A%E4%BF%A1%E7%A2%BA%E8%AA%8D

コードはこちらです。

$ 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]の部分には、[]や""を使わずに、貼り付けしています。

https://images.ctfassets.net/23aumh6u8s0i/346OJCiphrtCFAMqCDNhAT/610c50a0f000b57732652d152604c9f7/find-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_rawnilになっていることが問題なのかな...?といった感じです。
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日費やしたのですが、わからなかったので質問させていただきました。
どうぞよろしくお願いいたします。????‍♀️

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

Hey there,

I had (almost) this exact same setup and started getting this same error a few days ago. I was puzzled because everything worked fined until just a few days, but even more puzzled since my deployed apps where working fine, it was only in development or trying to reach the endpoints with Insomnia that I was getting the error.

I know this might not be the solution for your issue, and that you probably already moved on from it but I thought of pointing out that for this particular Auth0 setup the error is more than likely something very mundane.

In my case the issue was that I recently installed Lockbox because I decided to keep my previous bearer token stored on the database and have then encrypted. That was it. The token I was using to try my calls was ciphered, because I was grabbing it directly from the database, completely forgetting about Lockbox.

I debugged this by looking at the logs on the API app and seeing that the tokens coming from Insomnia where different than those coming from the running app making requests.

I reckon most people encountering this error will have some kind of issue relating to the bearer token passing as a misrepresentation.

Hope this helps in the future.

投稿2022/04/25 12:52

nhc

総合スコア4

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問