mr-timofey/laravel-simple-tokens

基于简单令牌和缓存的用户认证和授权

0.3.0 2020-05-02 15:11 UTC

This package is auto-updated.

Last update: 2024-09-29 05:01:38 UTC


README

基于简单令牌和缓存的用户认证和授权。

你厌倦了令人眼花缭乱的、不必要的复杂 Passport OAuth?你想找一些可配置、可管理且简单的?那么这正是你需要的包。

特性

  • 完全兼容 Eloquent 的 auth 驱动
  • 基于缓存的令牌授权,具有可配置的 TTL
  • 每个提供者都可以使用简单的 where/where in 子句或模型作用域进行额外的查询限制配置(例如,您可以仅限制特定用户角色的授权)
  • 控制器特质,以开箱即用的方式维护应用的认证/授权/注销逻辑(但您仍然需要定义控制器和路由)
  • 支持多个独立的守卫

要求

  • PHP 7.1
  • Laravel 5

安装

composer require mr-timofey/laravel-simple-tokens

对于 Laravel <= 5.4,将 MrTimofey\LaravelSimpleTokens\ServiceProvider 添加到您的 app.providers 配置文件中。

php artisan vendor:publish --provider="MrTimofey\LaravelSimpleTokens\ServiceProvider"

用法

将您的 auth.providers.users.driver 配置(如果需要,将 users 替换为其他提供者)设置为 simple。任何授权的 HTTP 请求都必须包含 Authorization: Bearer {api_token} 标头。

如有必要,请配置一个守卫(默认为 api)。

使用与您的 auth 控制器一起使用的 MrTimofey\LaravelSimpleTokens\AuthenticatesUsers 特质。此特质添加了以下方法

  • authenticate - 使用登录/电子邮件/密码/remember_token 认证用户并返回包含以下内容的 JSON 响应
     {
     	user: { /* user data */ },
     	api_token: 'api token string',
     	remember_token: 'remember token string or NULL if request does not have a "remember" flag'
     }
    此方法生成 api_token 并将其与 cache()->set('prefix:' . $token, $user_id, $ttl) 存入缓存。同时重新生成用户的 remember_token。TTL 在 simple_tokens.ttl 中配置。
  • logout - 从缓存中删除 api_token
  • user - 返回用户数据的 JSON。

您还可以定义一个 $guard 类字段以使用除了默认的 api 之外的任何守卫。

认证提供者配置

// config/auth.php

return [

	// ...

	'providers' => [
		// Simple example (suitable for most cases)
		'simple' => [
			'driver' => 'simple',
			'model' => App\User::class
		],
	
		// Advanced example
		'advanced' => [
			'driver' => 'simple',
			'model' => App\User::class,
			
			// Query modifiers
			'only' => [
				// only users with email = example@email.com
				'email' => 'example@email.com',
				// only users with ID 1, 2 or 3
				'id' => [1, 2, 3]
			],
			
			// Any model scope
			'scope' => 'scopeName',
			// ...or
			'scope' => [
				'scopeName',
				'scopeWithArguments' => ['arg1', 'arg2']
			],
			
			// Cache prefix can be configured if you want to use multiple independent providers.
			// This will allow clients to have multiple tokens (one per each unique prefix).
			// On the other hand, you can restrict users to have a sinlgle token by providing same prefix.
			// Default: no prefix
			// IMPORTANT: this prefix will be appended to the `simple_tokens.cache_prefix` config entry.
			'cache_prefix' => '',

			// Token expiration time in minutes.
			// You can overwrite default value from the `simple_tokens.token_ttl` config entry here.
			'token_ttl' => 60
		]
	],

	// ...

];