Authentication

Authentication

Introduction

All the classes of the Auth system live in the namespace Auth and is implemented as a reference structure for User Authentication in the \App\ namespace.

To note that additional Route Filters are also added to support this reference implementation, and the proper configuration of a valid ENCRYPT_KEY is required.

Being a Users Management, a Database is required and in scripts/nova_users.sql you will find the associated MySQL dump for a users table.

The App\Controllers\Users also implements a small private area for the authenticated User. The private area is a simple Dashboard and a Profile page, where the users have the ability to change their password.

Important: Nova‘s Authentication uses the new Database API and not the Helpers\Database. If you choose to use the Nova Authentication, you would need to use the new Database API in the whole application and to not touch the Helpers\Database instances.

Configuration

Nova aims to make implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at app/Config/Auth.php, which contains several well documented options for tweaking the behavior of the authentication facilities.

By default, Nova includes a User model in your app/Models directory which may be used with the default extended authentication driver, which uses Database\ORM.

If your application is not using ORM, you may use the database authentication driver which uses the Nova query builder.

Storing Passwords

The Nova Hash class provides secure Bcrypt hashing:

Hashing A Password Using Bcrypt

$password = Hash::make(‘secret‘);

Verifying A Password Against A Hash

if (Hash::check(‘secret‘, $hashedPassword))
{
    // The passwords match...
}

Checking If A Password Needs To Be Rehashed

if (Hash::needsRehash($hashed))
{
    $hashed = Hash::make(‘secret‘);
}

Authenticating Users

To log a user into your application, you may use the Auth::attempt method.

if (Auth::attempt(array(‘email‘ => $email, ‘password‘ => $password)))
{
    // User is authenticated there.
}

Take note that email is not a required option, it is merely used for an example. You should use whatever column name corresponds to a "username" in your database. The Redirect::intended function will redirect the user to the URL they were trying to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.

When the attempt method is called, the auth.attempt event will be fired. If the authentication attempt is successful and the user is logged in, the auth.login event will be fired as well.

Determining If A User Is Authenticated

To determine if the user is already logged into your application, you may use the check method:

if (Auth::check())
{
    // The user is logged in...
}

Authenticating A User And "Remembering" Them

If you would like to provide "remember me" functionality in your application, you may pass true as the second argument to the attempt method, which will keep the user authenticated indefinitely (or until they manually logout). Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token.

if (Auth::attempt(array(‘email‘ => $email, ‘password‘ => $password), true))
{
    // The user is being remembered...
}

Note: If the attempt method returns true, the user is considered logged into the application.

Determining If User Authed Via Remember

If you are "remembering" user logins, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:

if (Auth::viaRemember())
{
    //
}

Authenticating A User With Conditions

You also may add extra conditions to the authenticating query:

if (Auth::attempt(array(‘email‘ => $email, ‘password‘ => $password, ‘active‘ => 1)))
{
    // The user is active, not suspended, and exists.
}

Note: For added protection against session fixation, the user‘s session ID will automatically be regenerated after authenticating.

Accessing The Logged In User

Once a user is authenticated, you may access the User model / record:

$email = Auth::user()->email;

To retrieve the authenticated user‘s ID, you may use the id method:

$id = Auth::id();

To simply log a user into the application by their ID, use the loginUsingId method:

Auth::loginUsingId(1);

Validating User Credentials Without Login

The validate method allows you to validate a user‘s credentials without actually logging them into the application:

if (Auth::validate($credentials))
{
    //
}

Logging A User In For A Single Request

You may also use the once method to log a user into the application for a single request. No sessions or cookies will be utilized.

if (Auth::once($credentials))
{
    //
}

Logging A User Out Of The Application

Auth::logout();

Basic Usage

    public function postLogin()
    {
        // Retrieve the Authentication credentials.
        $credentials = Input::only(‘username‘, ‘password‘);

        // Prepare the ‘remember‘ parameter.
        $remember = (Input::get(‘remember‘) == ‘on‘);

        // Make an attempt to login the Guest with the given credentials.
        if(! Auth::attempt($credentials, $remember)) {
            // An error has happened on authentication.
            $status = __d(‘users‘, ‘Wrong username or password.‘);

            return Redirect::back()->withStatus($status, ‘danger‘);
        }

        // The User is authenticated now; retrieve his Model instance.
        $user = Auth::user();

        if (Hash::needsRehash($user->password)) {
            $password = $credentials[‘password‘];

            $user->password = Hash::make($password);

            // Save the User Model instance - used with the Extended Auth Driver.
            $user->save();

            // Save the User Model instance - used with the Database Auth Driver.
            //$this->model->updateGenericUser($user);
        }

        if($user->active == 0) {
            Auth::logout();

            // User not activated; logout and redirect him back.
            $status = __d(‘users‘, ‘There is a problem. Have you activated your Account?‘);

            return Redirect::back()->withStatus($status, ‘warning‘);
        }

        // Prepare the flash message.
        $status = __d(‘users‘, ‘<b>{0}</b>, you have successfully logged in.‘, $user->username);

        // Redirect to the User‘s Dashboard.
        return Redirect::to(‘admin/dashboard‘)->withStatus($status);
    }
时间: 2024-10-10 01:33:12

Authentication的相关文章

CAS Authentication failed!

在本机测试CAS与phpCAS客户端集成正常,但是部署到其他服务器上就不能正常运行了,提示"CAS Authentication failed!",如下图所示 才开始百思不得其解啊,然后重新检查一遍部署的配置文件,然后检查CAS的官方文档,查看配置是否少配置的了属性什么的,还检查了php的ext插件,发现php5只需要curl和openssl的php插件就足够了,最后终于在phpCAS的日志文件中发现了问题. 重日志中可以看到是由于连接超时照成的,然后登录的casPHP所在的主机,使用

使用su - root出现Authentication failure

使用su - root出现 Password: su: Authentication failure 原因:ubtun系统默认是没有激活root用户的 解决方法: 输入命令:sudo passwd root 显示 Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully 注意: (Enter new UNIX password: )不能和(Password: )输入的相同,如果

Google Authentication的实现 - Odoo 安全登录

在前边的一篇文章中,我们提到了利用二次验证增强Odoo登录的可靠性:http://www.cnblogs.com/kfx2007/p/6023991.html 今天我们来具体实现这一步: 后端的实现 我们需要一个地方来存储二次验证的安全码,拓展用户字段: class res_users(models.Model): _inherit='res.users' enable_google_auth = fields.Boolean(u'启用Google两步验证') otp_str = fields.

解决passwd: Authentication token manipulation error

passwd 命令修改用户密码出现passwd: Authentication token manipulation error 今天,在测试用户文件属性的时候,修改用户密码发现报此错误. 百度上搜结果: /etc/passwd 文件被锁定 /etc/passwd  /etc/shadow 文件不同步 磁盘空间不足 inode 满了 /etc/pam.d/passwd 相关动态库文件问题 结果,我都试过了,最后发现问题了,我之前不小心把 /etc/pam.d/文件夹内容全部删除过,后来进入恢复模

Disconnected: No supported authentication methods available (server sent: publickey)

安装Git客户端后,进行PULL时报如下错误 disconnected no supported authentication methods available(server sent: publickey,keyboard interactive)解决方案 因为TortoiseGit和Git的冲突 我们需要把TortoiseGit设置改正如下. 1.找到TortoiseGit -> Settings -> Network 2.将SSH client指向~\Git\usr\bin\ssh.e

SharePoint Claim base authentication EnsureUser 不带claim(i:0#.w|)user Failed

环境信息: 带有Form base authentication(FBA).Active Directory Federation Services(ADFS).以及windows Authentication的混合认证的SharePoint环境. 问题具体描述: 在该环境中,调用EnsureUser添加一个普通的AD user,sharepoint 会throw "The specified user userLoginName could not be found.",当然此处的u

Web API 基于ASP.NET Identity的Basic Authentication

今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms认证,很少有Claims认证(声明式认证),而我们在用ASP.NET Identity实现登录,认证,授权的时候采用的是Claims认证. 在Web API2.0中认证接口为IAuthenticationFilter,我们只需实现该接口就行.创建BasicAuthenticationAttribut

Global Azure启用Multi-factor Authentication配置介绍

说到Azure下的Multi-factor Authentication服务,其实很直观的可以大概了解其意思,在azure上的Multi-factor Authentication服务可以提供用户登录Azure portal进行多重身份验证的功能,用户除了输入正确的密码信息还需要设置需要验证一些自定义信息: 自定义信息分为:Mobile apps.Phone calls.Text messages等,具体见下吧: 我们首先登录azure portal,打开Multi-factor Authent

TortoiseGit disconnected: no supported authentication methods available(server sent:publickey)

之前一直用命令行,现在想用图形工具,TortoiseGit,安装后遇到错误 TortoiseGit disconnected: no supported authentication methods available(server sent:publickey) 解决方法 因为TortoiseGit和Git的冲突 我们需要把TortoiseGit设置改正如下. 1.找到TortoiseGit -> Settings -> Network 2.将SSH client指向~\Git\bin\ss

ubuntu 突然不能 sudo成功,报错su: Authentication failure

通过查看日志: /var/log/auth.log 报错: su[9959]: PAM unable to dlopen(pam_rootok.so): /lib/security/pam_rootok.so: cannot open shared object file: No such file or directory su[9959]: PAM adding faulty module: pam_rootok.so su[9959]: PAM unable to dlopen(pam_u