LoginSignup
3
4

More than 5 years have passed since last update.

AngularJSの$httpや$resourceでのリクエストにAuthorizationヘッダーでの認証を付加する

Last updated at Posted at 2015-06-25

個別のリクエストではなくインターセプターを使ってまとめて追加。
インターセプターを作って$httpProvider.interceptors配列に追加するだけ。
下記コードは、サーバからのtokenを取得済みなら、Authorizationヘッダーに追加してリクエストするようになる例。

auth_interceptor.coffee
"use strict"

angular.module("myApp")
.factory("AuthInterceptor", (AuthToken)->
  "request": (config) ->
    config.headers ?=  {}
    if AuthToken.isToken()
      #Authorizationへの記述形式は、サーバの認証方式による。例:Token token="abcdefg...."
      config.headers.Authorization = AuthToken.getTokenString()
    config
).config ($httpProvider)->
  $httpProvider.interceptors.push("AuthInterceptor")

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4