laravel Authentication and Security
Creating the user model
First of all, we need to define the model that is going to be used to represent the
users of our application. Laravel already provides you with sensible defaults inside
app/config/auth.php, where you change the model or table that is used to store
your user accounts.
It also comes with an existing User model inside app/models/User.php. For the
purposes of this application, we are going to simplify it slightly, remove certain
class variables, and add new methods so that it can interact with the Cat model:
use Illuminate\Auth\UserInterface;
class User extends Eloquent implements UserInterface {
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
public function cats(){
return $this->hasMany('Cat');
}
public function owns(Cat $cat){
return $this->id == $cat->owner;
}
public function canEdit(Cat $cat){
return $this->is_admin or $this->owns($cat);
}
}
Remember that an interface does not give any implementation details. It is nothing
more than a contract that specifies the names of the methods that a class should
define when it implements the interface, in this case, getAuthIdentifier()
and getAuthPassword(). These methods are used internally by Laravel when
authenticating a user. The next method, cats(), simply defines the has many
relationship with the Cat model. The last two methods will be used to check
whether a given Cat instance is owned or editable by the current User instance.
Creating the necessary database schema
Now that we have defined a User model, we need to create the database schema
for it and alter the existing cats table to add information about the owner. Start by
creating a new migration:
$ php artisan migrate:make create_users
And then define the up method with the necessary database columns:
Authentication routes and views
Let's now look at the new routes and views. We will start by making some amends to
the master layout (app/views/master.blade.php) to display the login link to guests
and the logout link to users who are logged in. To check whether a visitor is logged
in, we use the Auth::check() method:
<div class="container">
<div class="page-header">
<div class="text-right">
@if(Auth::check())
Logged in as
<strong>{{{Auth::user()->username}}}</strong>
{{link_to('logout', 'Log Out')}}
@else
{{link_to('login', 'Log In')}}
@endif
</div>
@yield('header')
</div>
@if(Session::has('message'))
<div class="alert alert-success">
{{Session::get('message')}}
</div>
@endif
@if(Session::has('error'))
<div class="alert alert-warning">
{{Session::get('error')}}
</div>
@endif
@yield('content')
</div>
This code replaces the contents of the <body> tag in our previous template file.
A section for any error messages was also included below the header.
The route to display this login form could not be easier:
Route::get('login', function(){
return View::make('login');
});
If you were curious as to where and why Laravel uses the make methods
in various places, it is only there to maintain PHP 5.3 compatibility, which
does not support class member access on instantiation, and therefore, does
not let you write return new View('login');.
The route that handles login attempts will simply pass the username and password
input values to the Auth::attempt method. When this method returns true, we
simply redirect the visitor to the intended location. If this fails, we redirect the user
back to where he came from with Redirect::back() with the input values and an
error message.
Route::post('login', function(){
if(Auth::attempt(Input::only('username', 'password'))) {
return Redirect::intended('/');
} else {
return Redirect::back()
->withInput()
->with('error', "Invalid credentials");
}
});
But how does Laravel know what our intended location was? If you open
app/filters.php and look at the auth filter, you will see that it redirects guests
to the login route with the Redirect::guest() method. This method stores the
requested path in a session variable, which is then used by the intended() method.
The parameter passed to this method is the fallback route to which users should be
redirected if there is no request path in the session information.
Note also that there is a filter called guest that does the opposite of
auth; you could use it on the login route if you wanted to prevent
logged-in users from accessing it. With this filter in place, logged-in users
will be redirected to the home page instead. You can change this behavior
inside app/filters.php.
laravel Authentication and Security的更多相关文章
- [PHP] 浅谈 Laravel Authentication 的 auth:api
auth:api 在 Laravel 的 Routing , Middleware , API Authentication 主题中都有出现. 一. 在 Routing 部分可以知道 auth:api ...
- [PHP] 浅谈 Laravel Authentication 的 guards 与 providers
从文档的简单介绍上来讲,有一些抽象. 个人感觉,对于概念上的大多数不理解主要还是来自于 文档不是讲设计思路,而是实际操作. 查看英文文档,通常来说可以给你最准确的直觉,而本地翻译一般比较字面或者带有理 ...
- [转]The NTLM Authentication Protocol and Security Support Provider
本文转自:http://davenport.sourceforge.net/ntlm.html#ntlmHttpAuthentication The NTLM Authentication Proto ...
- [不错]A step-by-step guide to enabling security, TLS/SSL, and PKI authentication in Elasticsearch
Now posted on the Elastic blog December 12, 2018 update: This article has been published on Elastic’ ...
- How-to: Enable User Authentication and Authorization in Apache HBase
With the default Apache HBase configuration, everyone is allowed to read from and write to all table ...
- 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事
Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...
- HttpClient(4.3.5) - HTTP Authentication
HttpClient provides full support for authentication schemes defined by the HTTP standard specificati ...
- cloud computing platform,virtual authentication encryption
Distributed Management Task Forcevirtual Ethernet port aggregator encryption,authenticating,local ac ...
- 一个HTTP Basic Authentication引发的异常
这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...
随机推荐
- C++四种强制类型转换关键字
C语言使用强制类型转换(Type Cast)很简单,不管什么类型的转换,形式都如下: TYPE b = (TYPE)a; c++提供了4种类型转换操作符来应对不同场合的应用. const_cast ...
- Poj OpenJudge 百练 2602 Superlong sums
1.Link: http://poj.org/problem?id=2602 http://bailian.openjudge.cn/practice/2602/ 2.Content: Superlo ...
- Ubuntu、Sql Server卸载心得
这几天真是搞得亏大了! 首先是卸载Ubuntu,直接在Windows下格式化那个盘了,这就出岔子了……然后越来越糟糕,最后弄得一个系统都没有了……然后重装系统…… 然后装VS和Sql Server,因 ...
- 个人站长如何使用svn发布到服务器不遗漏文件
作为个人站长,最最头疼的一件事情就是在本地开发好代码之后,上传的时候要去服务器上一个一个文件进行覆盖,添加操作:是人难免出错,避免这种情况的方法: 开发者最好是在本地有一个代码库,创建好代码库之后,至 ...
- rpm与yum命令的初步认识
RPM:Red Hat package manager(RedHat软件包管理工具),现在为RPM is Package Manager好比windows里的文件扩展名为·exe的软件包. RPM的包 ...
- Skyline中使用AxTE3DWindowEx打开新的一个球体
在winform窗体中拖入AxTE3DWindowEx控件. using system; using system.Collections.Generic; using System.Drawing; ...
- ARM-Linux S5PV210 UART驱动(5)----串口的open操作(tty_open、uart_open)
串口驱动初始化后,串口作为字符驱动也已经注册到系统了,/dev目录下也有设备文件节点了. 那接下来uart的操作是如何进行的呢? 操作硬件之前都是要先open设备,先来分析下这里的open函数具体做了 ...
- 解决WPF图片模糊最佳方法(绑定PixelWidth与PixelHeight)
从事WPF开发一年有余,对于图片显示模糊相信很多人都遇到过.网络上查找能得到一堆解决方法,但都是会带来其他负面影响得不到最佳效果.其实,有些图片会因为垂直分辨率/水平分辨率不同而造成在WPF界面上显示 ...
- 1028. List Sorting (25)
#include <vector> #include <stdio.h> #include <string.h> #include <algorithm> ...
- having count(*) > 1
select phone from aa group by phone having count(*) > 1 后面的having子句是什么意思啊? 以phone分组,分组后每组里面phone出 ...