認証

□未翻訳

□翻訳中

□翻訳完了(中垣健志)

■レビュー(細田謙二)

認証

RBACを使用するためには、ユーザーが識別される必要があります。これは、ユーザーが登録を行い(あるいは事前に登録されている状態で)、ログインする必要があることを意味しています。

In order to use RBAC, users need to be identified. This means that they need to register (or be registered) and log in.

Authは複数のログイン用メソッドを提供します。デフォルトのメソッドは、ローカルのauth_userテーブルに基づいてユーザーを識別します。代わりに、サードパーティの認証システムやシングルサインオンを提供するプロバイダ(Google、PAM、LDAP、Facebook、LinkedIn、OpenID、OAuth、その他)に対してユーザーをログインさせることができます。

Auth provides multiple login methods. The default one consists of identifying users based on the local auth_user table. Alternatively, it can log in users against third-party authentication systems and single sign on providers such as Google, PAM, LDAP, Facebook, LinkedIn, OpenID, OAuth, etc..

Authの使用を開始するには、少なくとも以下のコードをmodelファイルに用意する必要があります。このコードはまた、web2pyの"welcome"アプリケーションで提供され、db接続オブジェクトを利用しています:

To start using Auth, you need at least this code in a model file, which is also provided with the web2py "welcome" application and assumes a db connection object:

1.

2.

3.

from gluon.tools import Auth

auth = Auth(globals(), db)

auth.define_tables(username=False)

もしユーザーをメールアドレスではなくログイン時のユーザー名で認証したい場合、 username=Trueと設定します。

Set username=True if you want auth to user username for login instead of email.

Authを公開するには、次のような関数をコントローラに用意する必要があります("default.py"にサンプルがあります):

To expose Auth, you also need the following function in a controller (for example in "default.py"):

1.

def user(): return dict(form=auth())

authオブジェクトとuser関数の両方は雛形アプリケーションですでに定義されています。

The auth object and the user action are already defined in the scaffolding application.

web2pyにはまた、適切にこの関数をレンダリングするための次のようなサンプルビュー"welcome/views/default/user.html"が含まれています:

web2py also includes a sample view "welcome/views/default/user.html" to render this function properly that looks like this:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

{{extend 'layout.html'}}

<h2>{{=T( request.args(0).replace('_',' ').capitalize() )}}</h2>

<div id="web2py_user_form">

{{=form}}

{{if request.args(0)=='login':}}

{{if not 'register' in auth.settings.actions_disabled:}}

<br/><a href="{{=URL(r=request,args='register')}}">register</a>

{{pass}}

{{if not 'request_reset_password' in auth.settings.actions_disabled:}}

<br/><a href="{{=URL(r=request,args='request_reset_password')}}">lost password</a>

{{pass}}

{{pass}}

</div>

この関数はformを単純に表示しています。ですので、標準のフォームカスタマイズ用の構文を使ってカスタマイズすることが可能です。唯一の注意点は、form=auth()によって表示されているフォームがrequest.args(0)に依存していることです。つまり、もしデフォルトのauth()のログインフォームを独自のログインフォームに変更したい場合、以下のビューのようにif文を利用する必要があります:

Notice that this function simply displays a form and therefore it can be customized using normal custom form syntax. The only caveat is that the form displayed by form=auth()depends on request.args(0); therefore, if you replace the default auth() login form with a custom login form, you may need an if statement like this in the view:

1.

{{if request.args(0)=='login':}}...custom login form...{{pass}}

上記のコントローラは、複数のアクションを公開しています:

The controller above exposes multiple actions:

http://.../[app]/default/user/register

http://.../[app]/default/user/login

http://.../[app]/default/user/logout

http://.../[app]/default/user/profile

http://.../[app]/default/user/change_password

http://.../[app]/default/user/verify_email

http://.../[app]/default/user/retrieve_username

http://.../[app]/default/user/request_reset_password

http://.../[app]/default/user/reset_password

http://.../[app]/default/user/impersonate

http://.../[app]/default/user/groups

http://.../[app]/default/user/not_authorized

    • registerはユーザーの登録を行います。CAPTCHAも統合されていますが、デフォルトでは無効になっています。

    • loginは事前に登録されたユーザーのログインを許可します(検証が通るか必要ない場合に、承認が通るか必要ない場合に、ブロックされていない場合に許可します)。

    • logoutは期待通りの動きをしますが、その他のメソッドのように、イベントのログを記録し、他のイベントのトリガーとして使用することもできます。

    • profileは、ユーザーにプロファイルを編集することを許可します。プロファイルとはauth_userテーブルに登録された情報です。このテーブルは固定された構造を持っておらず、カスタマイズができることに注意してください。

    • change_passwordは、ユーザーにフェイルセーフな方法でパスワードを変更させることができます。

    • verify_email。電子メール検証が有効な場合、登録処理を行ったユーザーは、その電子メール情報を検証するためのリンクを含むメールを受け取ります。このリンクはこのアクションを指し示します。

    • retrieve_username。デフォルトでは、 Authは電子メールとパスワードを使用してログインしますが、電子メールの代わりにユーザー名を使うこともできます。後者のケースでは、もしユーザーがユーザー名を忘れた場合、retrieve_usernameメソッドによって、ユーザーにメールアドレスを入力させ、そのアドレスに送られたメールからユーザー名を取得することが可能になります。

    • request_reset_password。このメソッドでは、自分のパスワードを忘れてしまったユーザーが新しいパスワードを要求できます。ユーザーは、reset_passwordを指し示す確認メールを受け取ることになります。

    • impersonateは、あるユーザーを別の"偽装ユーザー"にすることができます。これは、デバッグと、サポートにとって重要な機能です。request.args[0]が偽装されたユーザーIDになります。このメソッドは、has_permission('impersonate', db_auth_user, user_id)として指定されたユーザーでログインした時のみ有効となります。

    • groupsは、現在ログオンしているユーザーが所属しているグループが一覧表示されます。

    • not_authorizedは、ユーザーが権限のないページを表示しようとした時に、エラーメッセージを表示します。

    • navbarは、ログインやユーザー登録を行うリンクを含むバーを生成するヘルパーです。

  • register allows users to register. It is integrated with CAPTCHA, although this is disabled by default.

  • login allows users who are registered to log in (if the registration is verified or does not require verification, if it has been approved or does not require approval, and if it has not been blocked).

  • logout does what you would expect but also, as the other methods, logs the event and can be used to trigger some event.

  • profile allows users to edit their profile, i.e. the content of the auth_user table. Notice that this table does not have a fixed structure and can be customized.

  • change_password allows users to change their password in a fail-safe way.

  • verify_email. If email verification is turned on, then visitors, upon registration, receive an email with a link to verify their email information. The link points to this action.

  • retrieve_username. By default, Auth uses email and password for login, but it can, optionally, use username instead of email. In this latter case, if a user forgets his/her username, the retrieve_username method allows the user to type the email address and retrieve the username by email.

  • request_reset_password. Allows users who forgot their password to request a new password. They will get a confirmation email pointing to reset_password.

  • impersonate allows a user to "impersonate" another user. This is important for debugging and for support purposes. request.args[0] is the id of the user to be impersonated. This is only allowed if the logged in userhas_permission('impersonate', db.auth_user, user_id).

  • groups lists the groups the current logged in user is a member of.

  • not_authorized displays an error message when the visitor tried to do something that he/she is not authorized to do

  • navbar is a helper that generates a bar with login/register/etc. links.

logout、profile、ch​​ange_password、impersonate、groupsは、ログインしている必要があります。

Logout, profile, change_password, impersonate, and groups require login.

デフォルトではこれらはすべて公開されますが、それらのアクションの一部のみにアクセスを制限することも可能です。

By default they are all exposed, but it is possible to restrict access to only some of these actions.

上記のすべてのメソッドは、Authのサブクラスを作成することで、拡張したり置き換えたりすることが可能です。

All of the methods above can be extended or replaced by subclassing Auth.

ログインした訪問者のみ関数にアクセスできるよう制限するためには、以下のサンプルのように関数にデコレータを指定します

To restrict access to functions to only logged in visitors, decorate the function as in the following example

1.

2.

3.

@auth.requires_login()

def hello():

return dict(message='hello %(first_name)' % auth.user)

全ての関数はデコレータを指定できます。公開されているものだけではありません。もちろんこれは、アクセスコントロールの非常に単純な例です。より複雑な例については後述します。

Any function can be decorated, not just exposed actions. Of course this is still only a very simple example of access control. More complex examples will be discussed later.

auth.user

auth.user_id

auth.userは、現在ログインしているユーザーに該当するdb.auth_userのレコードのコピーか、Noneを格納しています。またauth.user_idauth.user.idと同じ値(すなわち、現在ログインしているユーザーのID)かNoneになります。

auth.user contains a copy of the db.auth_user records for the current logged in user or None otherwise. There is also also a auth.user_id which is the same as auth.user.id (i.e. the id of the current logger in user) or None.

登録の制限

Restrictions on registration

訪問者が登録を行うことはできるが、管理者によって承認されるまでログインできないようにする場合:

If you want to allow visitors to register but not to log in until registration has been approved by the administrator:

1.

auth.settings.registration_requires_approval = True

appadminインターフェイスを介して、登録を承認することができます。auth_userテーブルを見てください。保留中の登録情報は、registration_keyフィールドに"pending"が設定されています。登録を承認するには、このフィールドを空白に設定します。

You can approve a registration via the appadmin interface. Look into the table auth_user. Pending registrations have a registration_key field set to "pending". A registration is approved when this field is set to blank.

appadminインターフェイスを介して、ユーザーをログインできないようにすることもできます。auth_userから該当のユーザーを見つけてregistration_keyを"blocked"に設定します。"blocked"となったユーザーは、ログインができません。ただし、ログインしていないユーザーからのログインを防ぐことははできますが、既にログインしているユーザーを強制的にログアウトさせることはできません。"disabled"を"blocked"の代わりに使用することもできます。動きは全く同じです。

Via the appadmin interface, you can also block a user from logging in. Locate the user in the table auth_user and set the registration_key to "blocked". "blocked" users are not allowed to log in. Notice that this will prevent a visitor from logging in but it will not force a visitor who is already logged in to log out. The word "disabled" may be used instead of "blocked" if preferred, with exactly the same behaviour.

また以下のステートメントを使用して完全に"登録"​​ページへのアクセスをブロックすることができます:

You can also block access to the "register" page completely with this statement:

1.

auth.settings.actions_disabled.append('register')

Authの他のメソッドも同じ方法で制限することができます。

Other methods of Auth can be restricted in the same way.

OpenIDやFacebookなどの認証との統合

Integration with OpenID, Facebook, etc.

Janrain

OpenID

Facebook

LinkedIn

Google

MySpace

Flickr

web2pyのロールベースのアクセス制御を使用して、OpenID、Facebook、LinkedIn、Google、MySpace、Flickr、などの外部サービスによる認証ができます。最も簡単な方法は、Janrain Engage(旧RPX)(Janrain.com)を使用することです。

You can use the web2py Role Base Access Control and authenticate with other services like OpenID, Facebook, LinkedIn, Google, MySpace, Flickr, etc. The easiest way is to use Janrain Engage (formerly RPX) (Janrain.com).

Janrain Engageはミドルウェアの認証を提供するサービスです。Janrain.comへの登録、そして使用するドメイン(あなたのアプリケーションの名前)と利用するURLの登録を行うことができます。そしてAPIキーが提供されます。

Janrain Engage is a service that provides middleware authentication. You can register with Janrain.com, register a domain (the name of your app) and set of URLs you will be using, and they will provide you with an API key.

では、あなたのweb2pyアプリケーションのモデルを編集して、以下の行をauthオブジェクトの定義より後ろに追加してください:

Now edit the model of your web2py application and place the following lines somewhere after the definition of the auth object :

1.

2.

3.

4.

5.

6.

from gluon.contrib.login_methods.rpx_account import RPXAccount

auth.settings.actions_disabled=['register','change_password','request_reset_password']

auth.settings.login_form = RPXAccount(request,

api_key='...',

domain='...',

url = "http://localhost:8000/%s/default/user/login" % request.application)

最初の行では新しいログインメソッドをインポートしています。2行目は、ローカルユーザーの登録を無効にしています。3行目はweb2pyに対してRPXのログインメソッドを使用するように指示しています。Janrain.comによって提供される独自のapi_key、登録する際に選択したドメイン、ログインページの外部urlを挿入する必要があります

The first line imports the new login method, the second line disables local registration, and the third line asks web2py to use the RPX login method. You must insert your own api_keyprovided by Janrain.com, the domain you choose upon registration and the external url of your login page.

新しいユーザーが最初にログインした時に、web2pyはそのユーザーに関連づけられた新規のdb.auth_userのレコードを作成します。registration_idフィールドが、ユーザーを一意に識別するIDとして設定されます。ほとんどの認証方法は、ユーザー名、電子メール、名前と名字を提供しますが、必ず提供されるとは限りません。どのフィールドを提供しているかは、ユーザーによって選択されたloginメソッドに依存します。もし同じユーザーが異なる認証のメカニズムを使ってログインした場合(例えば、OpenIDでログインしたあとにFacebookでログインし直した)Janrainは、それらを同じユーザーとしては認識せず、それぞれのregistration_idを発行します。

When a new user logins for the first time, web2py creates a new db.auth_user record associated to the user. It will use the registration_id field to store a unique id for the user. Most authentication methods will also provide a username, email, first_name and last_name but that is not guaranteed. Which fields are provided depends on the login method selected by the user. If the same user logs in twice using different authentication mechanisms (for example once with OpenID and once with Facebook), Janrain may not recognize his/her as the same user and issue different registration_id.

Janrainによって提供されるデータとdb.auth_userに保存されるデータとのマッピングは、カスタマイズすることができます。ここではFacebookを例として示します:

You can customize the mapping between the data provided by Janrain and the data stored indb.auth_user. Here is an example for Facebook:

1.

2.

3.

4.

5.

6.

auth.settings.login_form.mappings.Facebook = lambda profile:\

dict(registration_id = profile["identifier"],

username = profile["preferredUsername"],

email = profile["email"],

first_name = profile["name"]["givenName"],

last_name = profile["name"]["familyName"])

ディクショナリ内のキーは、db.auth_userのフィールドです。そして値は、Janrainによって提供されるプロファイルオブジェクトに存在するデータエントリです。後者の詳細については、オンラインJanrainのマニュアルをご覧ください。

The keys in the dictionary are fields in db.auth_user and the values are data entries in the profile object provided by Janrain. Look at the online Janrain documentation for details on the latter.

Janrainはまた、ユーザーのログインに関する統計情報を保持します。

Janrain will also keep statistics about your users' login.

このログインフォームは、web2pyのロールベースのアクセス制御と完全に統合されており、グループの作成、ユーザーのグループへの割り当て、権限の割り当て、ユーザーのブロック等を行うことができます。

This login form is fully integrated with web2py Role Based Access Control and you can still create groups, make users members of groups, assign permissions, block users, etc.

Janrainの無料の基本サービスでは、年間に2500人の登録ユーザーがサインインすることができます。より多くのユーザーへの対応するためには、支払いが必要となるサービス層の1つにアップグレードする必要があります。

Janrain's free Basic service allows up to 2500 unique registered users to sign in annually. Accommodating more users requires an upgrade to one of their paid service tiers.

Janrainではなく、他のログインメソッド(LDAP、PAM、Google、OpenID、OAuth/Facebook、LinkedIn、など)を必要とする場合は、それを利用することもできます。そのためのAPIは、本章の後半で記載します。

If you prefer not to use Janrain and want to use a different login method (LDAP, PAM, Google, OpenID, OAuth/Facebook, LinkedIn, etc.) you can do so. The API to do so are described later in the chapter.

CAPTCHAとreCAPTCHA

CAPTCHA and reCAPTCHA

CAPTCHA

reCAPTCHA

PIL

スパマーやボットによるあなたのサイトへの不要な登録を避けるため、登録用のCAPTHCAが必要になるときがあります。web2pyはreCAPTCHAをサポートしています。reCAPTCHAは、よく設計されていて、無料で、利便性がよく(訪問者が簡単に単語を読むことができる)、簡単に導入できて、その他のサードパーティー製のライブラリを必要としないからです。

To prevent spammers and bots registering on your site, you may require a registration CAPTCHA. web2py supports reCAPTCHA71 out of the box. This is because reCAPTCHA is very well designed, free, accessible (it can read the words to the visitors), easy to set up, and does not require installing any third-party libraries.

以下は、reCPATCHAを使う時に必要となることです。

    • reCPATCHAに登録を行い、登録アカウント用のパブリックキー, プライベートキーを入手してください。これらは単に二つの文字列です。

    • 次のコードをauthオブジェクトを定義した後にモデルに追加してください。

This is what you need to do to use reCAPTCHA:

  • Register with reCAPTCHA71 and obtain a (PUBLIC_KEY, PRIVATE_KEY) couple for your account. These are just two strings.

  • Append the following code to your model after the auth object is defined:

1.

2.

3.

from gluon.tools import Recaptcha

auth.settings.captcha = Recaptcha(request,

'PUBLIC_KEY', 'PRIVATE_KEY')

reCAPTCHAは、'localhost'や'127.0.0.1'というアドレスのサイトにアクセスした場合はうまく動かないかもしれません。外部に公開されたサイトでのみ動作するように登録されているからです。

reCAPTCHA may not work if you access the web site as 'localhost' or '127.0.0.1', because it is registered to work with publicly visible web sites only.

Recaptchaのコンストラクタは、二つの省略可能な引数をとります。

The Recaptcha constructor takes some optional arguments:

1.

Recaptcha(..., use_ssl=True, error_message='invalid')

use_ssl=Falseが初期値となっています。

Notice that use_ssl=False by default.

もし、reCAPTCHAを必要としない場合は、"gluon/tools.py"の中のRecaptchaクラスを見てください。他のCAPTCHAシステムを利用するのは簡単だからです。

If you do not want to use reCAPTCHA, look into the definition of the Recaptcha class in "gluon/tools.py", since it is easy to use other CAPTCHA systems.

Authのカスタマイズ

Customizing Auth

以下の呼び出しについて

The call to

1.

auth.define_tables()

この呼び出しは、まだ登録されていないAuthテーブルの定義を行います。つまり、独自のauth_userテーブルを定義することができるのです。以下に示すものと同様の構文に沿うことで、Authテーブルをカスタマイズできます。

defines all Auth tables that have not been defined already. This means that if you wish to do so, you can define your own auth_user table. Using a similar syntax to the one show below, you can customize any other Auth table.

以下は、ユーザーテーブルを定義するための適切な方法です。

Here is the proper way to define a user table:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

29.

30.

31.

# after

# auth = Auth(globals(),db)

db.define_table(

auth.settings.table_user_name,

Field('first_name', length=128, default=''),

Field('last_name', length=128, default=''),

Field('email', length=128, default='', unique=True),

Field('password', 'password', length=512,

readable=False, label='Password'),

Field('registration_key', length=512,

writable=False, readable=False, default=''),

Field('reset_password_key', length=512,

writable=False, readable=False, default=''),

Field('registration_id', length=512,

writable=False, readable=False, default=''))

custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table

custom_auth_table.first_name.requires = \

IS_NOT_EMPTY(error_message=auth.messages.is_empty)

custom_auth_table.last_name.requires = \

IS_NOT_EMPTY(error_message=auth.messages.is_empty)

custom_auth_table.password.requires = [IS_STRONG(), CRYPT()]

custom_auth_table.email.requires = [

IS_EMAIL(error_message=auth.messages.invalid_email),

IS_NOT_IN_DB(db, custom_auth_table.email)]

auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table

# before

# auth.define_tables()

フィールドはいくつでも追加することは可能ですが、このサンプルにある必須フィールドを除くことはできません。

You can add any field you wish, but you cannot remove the required fields shown in this example.

"password", "registration_key", "reset_password_key", "registration_id"フィールドをreadable=False and writable=False に設定することは重要です。訪問者が不正にこれらの値を変更できるようなことがあってはならないからです。

It is important to make "password", "registration_key", "reset_password_key" and "registration_id" fields readable=False and writable=False, since a visitor must not be allowed to tamper with them.

"username"というフィールドを追加した場合、これを"email"フィールドの代わりにログイン時に利用することができます。この場合、以下のようなバリデータを追加する必要があります。

If you add a field called "username", it will be used in place of "email" for login. If you do, you will need to add a validator as well:

1.

auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)

Authテーブルの名前変更

Renaming Auth tables

Auth テーブルの実際の名前は、次のように格納されています。

The actual names of the Auth tables are stored in

1.

2.

3.

4.

5.

auth.settings.table_user_name = 'auth_user'

auth.settings.table_group_name = 'auth_group'

auth.settings.table_membership_name = 'auth_membership'

auth.settings.table_permission_name = 'auth_permission'

auth.settings.table_event_name = 'auth_event'

これらの名前は auth オブジェクトの定義を行ってからAuthテーブルの定義を行うまでの間で再定義することにより変更できます。以下はその例です。

The names of the table can be changed by reassigning the above variables after the auth object is defined and before the Auth tables are defined. For example:

1.

2.

3.

4.

auth = Auth(globals(),db)

auth.settings.table_user_name = 'person'

#...

auth.define_tables()

実際のテーブルは以下のコードにより、その実際の名前とは独立して参照することができます。

The actual tables can also be referenced, independently of their actual names, by

1.

2.

3.

4.

5.

auth.settings.table_user

auth.settings.table_group

auth.settings.table_membership

auth.settings.table_permission

auth.settings.table_event

その他のログイン方法とログインフォーム

Other Login Methods and Login Forms

LDAP

PAM

Authは複数のログイン方法と新しいログイン方法を作成するためのフックを提供します。サポートされている各ログイン方法は、次のフォルダ内の一つのファイルに対応しています。

Auth provides multiple login methods and hooks to create new login methods. Each supported login method corresponds to a file in the folder

1.

gluon/contrib/login_methods/

各ログイン方法に関しては、ファイル自身に記述された説明を参照してください。ただし、ここではいくつかの例を用意します。

Refer to the documentation in the files themselves for each login method, but here are some examples.

まず、以下の二つの異なるタイプのログイン方法の違いを理解する必要があります。

  • web2pyのログインフォームを使ったログイン方法(ただし、認証情報はweb2pyの外で検証される)。例:LDAP

  • 外部のシングルサインオン用フォームを必要とするログイン方法(例:GoogleやFacebook)

First of all, we need to make a distinction between two types of alternate login methods:

  • login methods that use a web2py login form (although the credentials are verified outside web2py). An example is LDAP.

  • login methods that require an external single-sign-on form (an example is Google and Facebook).

後者の場合は、web2pyはログイン用の認証情報を取得せず、サービスプロバイダから発行されたログイン用のトークンのみを取得します。このトークンは、 db.auth_user.registration_idに保存されます。

In the latter case, web2py never gets the login credentials, only a login token issued by the service provider. The token is stored in db.auth_user.registration_id.

それでは、最初の例を見てみましょう。

Let's consider examples of the first case:

Basic

Basic

例えば認証が必要なサービスを用意するとき、以下のようなURLを

Let's say you have an authentication service, for example at the url

https://basic.example.com

ベーシック認証により受け入れるようにします。これは、サーバが以下のようなヘッダ情報をフォームに持つHTTPを受けとることを意味します。

that accepts basic access authentication. That means the server accepts HTTP requests with a header of the form:

1.

2.

3.

GET /index.html HTTP/1.0

Host: basic.example.com

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

ここで、後半の文字列はbase64でエンコーディングされたユーザー名:パスワードの文字列です。このサービスは、ユーザーが認証に成功した場合は200 OKを、それ以外の場合は400, 401, 402, 403あるいは404を返します。

where the latter string is the base64 encoding of the string username:password. The service responds 200 OK if the user is authorized and 400, 401, 402, 403 or 404 otherwise.

基本的なAuth のログインフォームを使ってユーザー名とパスワードを入力させて、そのようなサービスに対して認証情報を検証したいとします。この場合は、単にアプリケーションに以下のコードを挿入するだけで十分です。

You want to enter username and password using the standard Auth login form and verify the credentials against such a service. All you need to do is add the following code to your application

1.

2.

3.

from gluon.contrib.login_methods.basic_auth import basic_auth

auth.settings.login_methods.append(

basic_auth('https://basic.example.com'))

auth.settings.login_methods は、順番に実行される認証方法のリストです。デフォルでは以下のように設定されています。

Notice that auth.settings.login_methods is a list of authentication methods that are executed sequentially. By default it is set to

1.

auth.settings.login_methods = [auth]

代替の認証方法(例えば basic_auth)が追加された場合、Auth はまずauth_userの中身に基づいて訪問者の認証を試みます。認証に失敗した場合は、このリストに含まれる次の方法で認証を試みます。もし認証に成功して、かつauth.settings.login_methods[0]==authとなるとき、Auth は以下の処理を実行します:

    • もしauth_userにユーザーが存在しない場合、新しいユーザーが作成され、username/emailとpasswordが保存されます。

    • もしauth_userにユーザーが存在するが、入力された新しいパスワードが古いパスワードと一致しない場合、古いパスワードは新しいものに置き換わります(特に指定しない限り、パスワードは常にハッシュ化されたものが保存されます)。

When an alternate method is appended, for example basic_auth, Auth first tries to log in the visitor based on the content of auth_user, and when this fails, it tries the next method in the list. If a method succeeds in logging in the visitor, and ifauth.settings.login_methods[0]==auth, Auth takes the following actions:

  • if the user does not exist in auth_user, a new user is created and the username/email and passwords are stored.

  • if the user does exist in auth_user but the new accepted password does not match the old stored password, the old password is replaced with the new one (notice that passwords are always stored hashed unless specified otherwise).

新しいパスワードをauth_userに保存したくない場合は、ログイン方法の順番を変更すれば十分です。もしくは、auth をリストから削除します。以下はその例です:

If you do not wish to store the new password in auth_user, then it is sufficient to change the order of login methods, or remove auth from the list. For example:

1.

2.

3.

from gluon.contrib.login_methods.basic_auth import basic_auth

auth.settings.login_methods = \

[basic_auth('https://basic.example.com')]

ここで記載した他の全てのログイン方法についても同様です。

The same applies for any other login method described here.

SMTPとGmail

SMTP and Gmail

SMTP

Gmail

ログイン用の認証情報をリモートのSMTPサーバ(例えばGmail)を用いて検証することができます。すなわち、ユーザーの提供するemailとパスワードがGmailのSMTPサーバ (smtp.gmail.com:587)に正常にアクセスできる認証情報であればユーザーをログインさせることができます。これに必要なのは以下のコードだけです:

You can verify login credentials using a remote SMTP server, for example Gmail; i.e., you log the user in if the email and password they provide are valid credentials to access the Gmail SMTP server (smtp.gmail.com:587). All that is needed is the following code:

1.

2.

3.

from gluon.contrib.login_methods.email_auth import email_auth

auth.settings.login_methods.append(

email_auth("smtp.gmail.com:587", "@gmail.com"))

email_authの最初の引数は、SMTPサーバの"address:port"です。二つ目の引数はメールのドメインです。

The first argument of email_auth is the address:port of the SMTP server. The second argument is the email domain.

これは、TLS認証を必要とする任意のSMTPサーバに対しても動作します。

This works with any SMTP server that requires TLS authentication.

TLS

PAM

PAM

PAM

Pluggable Authentication Modules(PAM)を使った認証は、前のケースと同様に機能します。これにより、オペレーティングシステムのアカウントを用いてユーザーの認証ができるようになります:

Authentication using Pluggable Authentication Modules (PAM) works as in the previous cases. It allows web2py to authenticate users using the operating system accounts:

1.

2.

from gluon.contrib.login_methods.pam_auth import pam_auth

auth.settings.login_methods.append(pam_auth())

LDAP

LDAP

LDAP

LDAPを使った認証は、前のケースと全く同様に機能します。

Authentication using LDAP works very much as in the previous cases.

LDAPをMS Active Directoryとともに使用する方法です:

To use LDAP login with MS Active Directory:

Active Directory

1.

2.

3.

4.

from gluon.contrib.login_methods.ldap_auth import ldap_auth

auth.settings.login_methods.append(ldap_auth(mode='ad',

server='my.domain.controller',

base_dn='ou=Users,dc=domain,dc=com'))

LDAPをLotus NotesとDominoとともに使用する方法です:

To use LDAP login with Lotus Notes and Domino:

Lotus Notes

Domino

1.

2.

auth.settings.login_methods.append(ldap_auth(mode='domino',

server='my.domino.server'))

LDAPをOpenLDAP(UIDによる)とともに使用する方法です:

To use LDAP login with OpenLDAP (with UID):

OpenLDAP

1.

2.

auth.settings.login_methods.append(ldap_auth(server='my.ldap.server',

base_dn='ou=Users,dc=domain,dc=com'))

LDAPをOpenLDAP(CNによる)とともに方法です:

To use LDAP login with OpenLDAP (with CN):

1.

2.

auth.settings.login_methods.append(ldap_auth(mode='cn',

server='my.ldap.server', base_dn='ou=Users,dc=domain,dc=com'))

Google App Engine

Google App Engine

GAE login

Google App Engine上で動作しているアプリケーションでGoogleによる認証を行う場合には、web2pyのログインフォームによる認証は行わず、Googleのログインページにリダイレクトを行い、そして成功したら元のページに戻るようにします。前述の例とは動作が異なるため、APIは少し異なります。

Authentication using Google when running on Google App Engine requires skipping the web2py login form, being redirected to the Google login page, and back upon success. Because the behavior is different than in the previous examples, the API is a little different.

1.

2.

from gluon.contrib.login_methods.gae_google_login import GaeGoogleAccount

auth.settings.login_form = GaeGoogleAccount()

OpenID

OpenID

OpenID

(OpenIDのサポートがある)Janrainの組み込みについて説明しましたが、これが最も簡単なOpenIDを使う方法です。しかし、サードパーティー製のサービスに頼るのではなく、OpenIDプロバイダにその利用者(あなたのアプリケーション)から直接アクセスしたいこともあります。

We have previously discussed integration with Janrain (which has OpenID support) and that is the easiest way to use OpenID. Yet sometimes you do not want to rely on a third party service and you want to access the OpenID provider directly from the consumer (your app).

これは、その例です。

Here is an example:

1.

2.

from gluon.contrib.login_methods.openid_auth import OpenIDAuth

auth.settings.login_form = OpenIDAuth(auth)

OpenIDAUth を使うには、別途"python-open"のインストールが必要となります。

OpenIDAUth requires the "python-open" installed separately.

内部では、このログイン方法は次のようなテーブルを定義します。

Under the hood, this login method defines the following table

1.

2.

3.

4.

db.define_table('alt_logins',

Field('username', length=512, default=''),

Field('type', length =128, default='openid', readable=False),

Field('user', self.table_user, readable=False))

このテーブルには、各ユーザーのopenidのユーザー名が保存されます。現在ログインしているユーザーのopenidを表示したい場合は、次のようにします。

which stores the openid usernames for each user. If you want to display the openids for the current logged in user:

1.

{{=auth.settings.login_form.list_user_openids()}}

OAuth2.0とFacebook

OAuth2.0 and Facebook

OAuth

Facebook

(Facebookのサポートがある)Janrainの組み込みについて説明しましたが、サードパーティー製のサービスに頼るのではなく、OAuth2.0プロバイダ(例えばFacebook)にその利用者(あなたの作成するアプリケーション)から直接アクセスしたいこともあります。方法は以下の通りです。

We have previously discussed integration with Janrain (which has Facebook support), yet sometimes you do not want to rely on a third party service and you want to access a OAuth2.0 provider directly; for example, Facebook. Here is how:

1.

2.

from gluon.contrib.login_methods.oauth20_account import OAuthAccount

auth.settings.login_form=OAuthAccount(globals(),YOUR_CLIENT_ID,YOUR_CLIENT_SECRET)

自分自身のアプリケーションではなく、特定のFacebookアプリケーションにそのAPIにアクセスしようとログインするためにFacebook OAuth2.0を用いたい場合は、少し複雑になります。ここに、Facebook Graph APIにアクセスするための例を示します。

Things get a little more complex if you want to use Facebook OAuth2.0 to login into a specific Facebook app to access its API, instead of your own app. Here is an example for accessing the Facebook Graph API.

始めに、"pyfacebook"モジュールをインストールする必要があります。

First of all you must install the "pyfacebook" module.

そして、モデルに以下のコードを追加します。

Second, you need the following code in your model:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

29.

30.

31.

32.

33.

# import required modules

from facebook import GraphAPI

from gluon.contrib.login_methods.oauth20_account import OAuthAccount

# extend the OAUthAccount class

class FaceBookAccount(OAuthAccount):

"""OAuth impl for FaceBook"""

AUTH_URL="https://graph.facebook.com/oauth/authorize"

TOKEN_URL="https://graph.facebook.com/oauth/access_token"

def __init__(self, g):

OAuthAccount.__init__(self, g,

YOUR_CLIENT_ID,

YOUR_CLIENT_SECRET,

self.AUTH_URL,

self.TOKEN_URL)

self.graph = None

# override function that fetches user info

def get_user(self):

"Returns the user using the Graph API"

if not self.accessToken():

return None

if not self.graph:

self.graph = GraphAPI((self.accessToken()))

try:

user = self.graph.get_object("me")

return dict(first_name = user['first_name'],

last_name = user['last_name'],

username = user['id'])

except GraphAPIError:

self.session.token = None

self.graph = None

return None

# use the above class to build a new login form

auth.settings.login_form=FaceBookAccount(globals())

LinkedIn

LinkedIn

LinkedIn

(LinkedInのサポートがある)Janrainの組み込みについて説明しましたが、これが最も簡単なOAuthを使った方法です。しかし、サードパーティー製のサービスに頼るのではなく、Janrainプロバイダが提供するよりも多くの情報を得たいためにLinkedInに直接アクセスしたい場合もあります。

We have previously discussed integration with Janrain (which has LinkedIn support) and that is the easiest way to use OAuth. Yet sometime you do not want to rely on a third party service or you may want to access LinkedIn directly to get more information than Janrain provides.

方法は以下の通りです。

Here is an example:

1.

2.

from gluon.contrib.login_methods.linkedin_account import LinkedInAccount

auth.settings.login_form=LinkedInAccount(request,KEY,SECRET,RETURN_URL)

LinkedInAccount は"python-linkedin" モジュールを別途インストールする必要があります。

LinkedInAccount requires the "python-linkedin" module installed separately.

Multiple Login フォーム

Multiple Login Forms

ログイン方法の中には、login_formを変更するものとしないものがあります。変更する場合は、他と共存することができないかもしれません。ただし、同じページに複数のログインフォームを提供することで共存させることができます。web2pyは、そのための方法を提供しています。ここに、通常のログイン(auth)とRPXログイン(janrain.com)を共存させる例を示します。

Some login methods modify the login_form, some do not. When they do that, they may not be able to coexist. Yet some some coexist by providing multiple login forms in the same page. web2py provides a way to do it. Here is an example mix normal login (auth) and RPX login (janrain.com):

1.

2.

3.

4.

from gluon.contrib.login_methods.extended_login_form import ExtendedLoginForm

other_form = RPXAccount(request, api_key='...', domain='...', url='...')

auth.settings.login_form = ExtendedLoginForm(request,

auth, other_form, signals=['token'])

もしシグナルが設定され、リクエストに含まれるパラメータがいずれかのシグナルにマッチした場合、代わりにother_form.login_form への呼び出しを返します。other_form は、特別な状況をハンドルします。例えばother_form.login_formに含まれるOpenIDの複数のステップです。

If signals are set and a parameter in request matches any signals, it will return the call ofother_form.login_form instead. other_form can handle some particular situations, for example, multiple steps of OpenID login inside other_form.login_form.

そうでない場合は、other_formと共に通常のログインフォームが描画されます。

Otherwise it will render the normal login form together with the other_form.