Created
March 27, 2020 09:45
-
-
Save ssi-anik/f60d8e4561fc365d048a969f9a159eb2 to your computer and use it in GitHub Desktop.
[Laravel] - simple API token authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Database\Migrations\Migration; | |
class AddUserApiTokenField extends Migration | |
{ | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up() | |
{ | |
Schema::table('users', function (Blueprint $table) { | |
$table->string('api_token', 60)->unique(); | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
Schema::table('users', function (Blueprint $table) { | |
$table->dropColumn('api_token'); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="{{ config('app.locale') }}"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<!-- CSRF Token --> | |
<meta name="csrf-token" content="{{ csrf_token() }}"> | |
@if (auth()->check()) | |
<meta name="api-token" content="{{ auth()->user()->api_token }}"> | |
@endif | |
<title>{{ config('app.name', 'Laravel') }}</title> | |
<!-- Styles --> | |
<link href="{{ asset('css/app.css') }}" rel="stylesheet"> | |
</head> | |
<body> | |
<div id="app"> | |
<nav class="navbar navbar-default navbar-static-top"> | |
<div class="container"> | |
<div class="navbar-header"> | |
<!-- Collapsed Hamburger --> | |
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse"> | |
<span class="sr-only">Toggle Navigation</span> | |
<span class="icon-bar"></span> | |
<span class="icon-bar"></span> | |
<span class="icon-bar"></span> | |
</button> | |
<!-- Branding Image --> | |
<a class="navbar-brand" href="{{ url('/') }}"> | |
{{ config('app.name', 'Laravel') }} | |
</a> | |
</div> | |
<div class="collapse navbar-collapse" id="app-navbar-collapse"> | |
<!-- Left Side Of Navbar --> | |
<ul class="nav navbar-nav"> | |
| |
</ul> | |
<!-- Right Side Of Navbar --> | |
<ul class="nav navbar-nav navbar-right"> | |
<!-- Authentication Links --> | |
@if (Auth::guest()) | |
<li><a href="{{ route('login') }}">Login</a></li> | |
<li><a href="{{ route('register') }}">Register</a></li> | |
@else | |
<li class="dropdown"> | |
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> | |
{{ Auth::user()->name }} <span class="caret"></span> | |
</a> | |
<ul class="dropdown-menu" role="menu"> | |
<li> | |
<a href="{{ route('logout') }}" | |
onclick="event.preventDefault(); | |
document.getElementById('logout-form').submit();"> | |
Logout | |
</a> | |
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> | |
{{ csrf_field() }} | |
</form> | |
</li> | |
</ul> | |
</li> | |
@endif | |
</ul> | |
</div> | |
</div> | |
</nav> | |
@yield('content') | |
</div> | |
<!-- Scripts --> | |
<script src="{{ asset('js/app.js') }}"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window._ = require('lodash'); | |
/** | |
* We'll load jQuery and the Bootstrap jQuery plugin which provides support | |
* for JavaScript based Bootstrap features such as modals and tabs. This | |
* code may be modified to fit the specific needs of your application. | |
*/ | |
try { | |
window.$ = window.jQuery = require('jquery'); | |
require('bootstrap-sass'); | |
} catch (e) {} | |
/** | |
* We'll load the axios HTTP library which allows us to easily issue requests | |
* to our Laravel back-end. This library automatically handles sending the | |
* CSRF token as a header based on the value of the "XSRF" token cookie. | |
*/ | |
window.axios = require('axios'); | |
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; | |
/** | |
* Next we will register the CSRF Token as a common header with Axios so that | |
* all outgoing HTTP requests automatically have it attached. This is just | |
* a simple convenience so we don't have to attach every token manually. | |
*/ | |
let token = document.head.querySelector('meta[name="csrf-token"]'); | |
if (token) { | |
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; | |
} else { | |
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); | |
} | |
let api_token = document.head.querySelector('meta[name="api-token"]'); | |
if (api_token) { | |
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + api_token.content; | |
} | |
/** | |
* Echo exposes an expressive API for subscribing to channels and listening | |
* for events that are broadcast by Laravel. Echo and event broadcasting | |
* allows your team to easily build robust real-time web applications. | |
*/ | |
// import Echo from 'laravel-echo' | |
// window.Pusher = require('pusher-js'); | |
// window.Echo = new Echo({ | |
// broadcaster: 'pusher', | |
// key: 'your-pusher-key' | |
// }); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="container"> | |
<div class="row"> | |
<div class="col-md-8 col-md-offset-2"> | |
<div class="panel panel-default"> | |
<div class="panel-heading">Example Component</div> | |
<div class="panel-body"> | |
Hello {{ user.name }}<br> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
'user': {}, | |
}; | |
}, | |
mounted() { | |
axios.get('/api/user') | |
.then((response) => { | |
this.user = response.data; | |
}); | |
}, | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@extends('layouts.app') | |
@section('content') | |
<example></example> | |
@endsection |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\Auth; | |
use App\User; | |
use App\Http\Controllers\Controller; | |
use Illuminate\Support\Facades\Validator; | |
use Illuminate\Foundation\Auth\RegistersUsers; | |
class RegisterController extends Controller | |
{ | |
/* | |
|-------------------------------------------------------------------------- | |
| Register Controller | |
|-------------------------------------------------------------------------- | |
| | |
| This controller handles the registration of new users as well as their | |
| validation and creation. By default this controller uses a trait to | |
| provide this functionality without requiring any additional code. | |
| | |
*/ | |
use RegistersUsers; | |
/** | |
* Where to redirect users after registration. | |
* | |
* @var string | |
*/ | |
protected $redirectTo = '/home'; | |
/** | |
* Create a new controller instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
$this->middleware('guest'); | |
} | |
/** | |
* Get a validator for an incoming registration request. | |
* | |
* @param array $data | |
* @return \Illuminate\Contracts\Validation\Validator | |
*/ | |
protected function validator(array $data) | |
{ | |
return Validator::make($data, [ | |
'name' => 'required|string|max:255', | |
'email' => 'required|string|email|max:255|unique:users', | |
'password' => 'required|string|min:6|confirmed', | |
]); | |
} | |
/** | |
* Create a new user instance after a valid registration. | |
* | |
* @param array $data | |
* @return User | |
*/ | |
protected function create(array $data) | |
{ | |
return User::create([ | |
'name' => $data['name'], | |
'email' => $data['email'], | |
'password' => bcrypt($data['password']), | |
'api_token' => str_random(60), | |
]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Notifications\Notifiable; | |
use Illuminate\Foundation\Auth\User as Authenticatable; | |
class User extends Authenticatable | |
{ | |
use Notifiable; | |
/** | |
* The attributes that are mass assignable. | |
* | |
* @var array | |
*/ | |
protected $fillable = [ | |
'name', 'email', 'password', 'api_token', | |
]; | |
/** | |
* The attributes that should be hidden for arrays. | |
* | |
* @var array | |
*/ | |
protected $hidden = [ | |
'password', 'remember_token', | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment