dou426098 2014-06-01 10:15
浏览 52

CakePHP基本身份验证和jQuery

I'm trying to implement Basic Authentication in CakePHP with an application written entirely in jQuery. I was going to use OAuth2, but got fed up with the added complexity and seen as this application will be the only thing using the API, Basic Auth should be sufficient.

The login method looks like:

login: function(username, password) {    
    $.ajax({
        type: 'GET',
        url: 'http://api.domain.com/login',
        beforeSend : function(xhr) {
            var base64 = $.base64.encode(username + ':' + password);
            xhr.setRequestHeader("Authorization", "Basic " + base64);
        },
        dataType: 'jsonp',
        success: function(data) {
            if( data.response.status == 'error' ) {
                alert(data.response.message);
            } else {                
                // Save some sort of session                   
            }
        },
        error: function(a,b,c) {
            console.log(a,b,c);
        }
    });        
}

And on the CakePHP side:

public function login() {    
    if ($this->request->is('get')) {        
        if ($this->Auth->login()) {            
            $response = json_encode(
                array(
                    'meta'=>array(
                        'code'=>$this->response->statusCode(),
                        'in'=>round(microtime(true) - TIME_START, 4)
                    ),
                    'response'=>array(
                        'status'=>'success',
                        'message'=>'successfully logged in'
                    )
                )
            );                
        } else {   
            $response = json_encode(
                array(
                    'meta'=>array(
                        'code'=>$this->response->statusCode(),
                        'in'=>round(microtime(true) - TIME_START, 4)
                    ),
                    'response'=>array(
                        'status'=>'error',
                        'message'=>'incorrect login details'
                    )
                )
            );   
        }           
        // Handle JSONP
        if(isset($_GET['callback'])) {
            $response = $_GET['callback'] . '(' . $response . ')';
        }       
        // Return JSON
        $this->autoRender = false;
        $this->response->type('json');
        $this->response->body($response);           
    }       
}
  1. How do I save the user login details? As I can't create a session because the JavaScript MIGHT not be running on the same server (as it could be an external application, mobile app, etc.) The data WILL be being sent over SSL, but I'm not sure how I can remember user details, so the user doesn't have to keep logging in. As far as I know Basic Authentication is supposed to be stateless... so no cookies or sessions will even exist. Can anyone shed light on this?

Update: After doing some more research into this, I've found that the username and password needs sending with each request... so in effect there NEVER is a session or cookie. But I'd need to store this information somewhere? Otherwise the user would be logging in after every request on the page right?

  1. Once the user has logged in and is now authenticated... how can I make requests to data and handle the authentication to make sure the correct user has access, and if they create data that is created as them. As in OAuth2, I would have an access_token I could just pass to access data, but in Basic Auth, you don't have a token. And because there is no session, I can't access the logged in users information. So how do I do this?

  2. According to the CakePHP docs, you don't need a login method (for Basic Auth) in CakePHP 2.4+ so how exactly does the user login from the Client side and what controller method would I talk to when passing the username and password?

Update: When trying to access the login method based on my code above, I get the prompt for a username and password... but this is an allowed method! Any ideas why? As it prevents my JavaScript from sending the request as the endpoint can never be accessed. Also if I login using the prompt I remain logged in even if I visit the logout method or clear all my sessions/caches in the browser. So how do I delete a users login?

Any help to point me in the right direction would be much appreciated, as it feels I'm completely misunderstanding the way Basic Auth works... Some examples would be awesome!

Update 2:

According to the PHP Docs, the following is the way to check if a user is logged in or not and show a message if they cancel. The information is also stored without ANY USE of a session! So how does this same principle apply to CakePHP? For example, how do I show the correct 401 status and a custom message, how is the logged in user info stored in CakePHP if it's based on this?

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
  • 写回答

2条回答 默认 最新

  • doubaoxue5788 2014-06-03 11:13
    关注

    Sessions can be used without cookies, share it as a parameter in the each query, and as the value of json response.

    1. Prepare your application to store sessionID in database or cache

    2. after successful ajax login, in the json response include the sessionID

    3. every next request must contain the sessionID as a parameter, the response must also include a sessionID

    This is how I would do.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器