简体   繁体   English

从其他域中的应用程序登录RESTful Laravel API

[英]RESTful Laravel API login from application in other domain

How to config Laravel 5.0 to login from other domain? 如何配置Laravel 5.0从其他域登录? Explain, we have a Laravel RESTful API, and some users creates Angular.js apps and host on your own domains. 说明一下,我们有一个Laravel RESTful API,有些用户在你自己的域上创建Angular.js应用程序和托管。

When try to login through these apps, login returns true, but on next request lose the session. 当尝试登录这些应用程序时,登录返回true,但在下一个请求时会丢失会话。

I think that can be related to CORS, but I set the correct headers. 我认为这可能与CORS有关,但我设置了正确的标题。

My Headers: 我的标题:

Hearders setted on apache virtualhost: 在apache虚拟主机上设置的Hearders:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, PUT, PATCH, DELETE"
Header always add Access-Control-Allow-Headers "accept, origin, x-requested-with, content-type, x-application-token, x-csrf-token, x-password-reset-token"
Header always add Access-Control-Expose-Headers "x-csrf-token"

Setting CORS is only a small step in making this work. 设置CORS只是使这项工作迈出的一小步。 Please give this article a read 请阅读本文

The problem you are experiencing is subsequent requests from your other domains aren't sending any kind of token or identifier that laravel can use to decide what user is making the request. 您遇到的问题是来自其他域的后续请求不会发送任何类型的令牌或标识符,laravel可以使用这些令牌或标识符来决定用户正在发出请求。 You should look into using a JWT library. 您应该考虑使用JWT库。

laravel-jwt is pretty solid for accomplishing this. laravel-jwt对于实现这一点非常可靠。 Simply adding CORS into your app won't be enough for it to work properly. 简单地将CORS添加到您的应用程序中将不足以使其正常工作。

Laravel needs to know what user is making the request and the above library comes with middleware and methods to easily accomplish this. Laravel需要知道用户在做什么请求,上面的库附带了中间件和方法来轻松实现这一点。

From a high level, some of the steps that will need to occur are: 从较高的层面来看,需要发生的一些步骤是:

1) Setting up your angular login controller/service 1)设置角度登录控制器/服务

    $scope.login = function () {

        // Send The Login Request
        UserService.authenticate($scope.formData)
            .$promise.then(function(data) {

                // If Successfully Authed
                if (data.success && data.hasOwnProperty('token')) {

                    // Set Cookies
                    UserService.setCurrentUser(data.user);
                    UserService.setUserToken(data.token);                        

                    // Fire Login Event
                    return authService.loginConfirmed(data);

                } else {
                    // Else Errors Logging In
                    AlertService.addAlert(data.error, 'danger');
                }
            });
        };

2) Handling the auth with laravel-jwt: 2)使用laravel-jwt处理auth:

public function authenticate()
{
    $credentials = $this->request->only('username', 'password');

    try {
        // Verify Credentials & Create Token for User
        if (! $token = $this->auth->attempt($credentials)) {
            return response()->json(['success' => false, 'error' => 'Invalid Credentials.'], 401);
        }
    } catch(JWTException $e) {
        // Something went wrong encoding the token.
        return response()->json(['success' => false, 'error' => 'Could not create token.'], 401);
    }

    return response()->json(['success' => true, 'user' => $user->toArray());

}

3) Adding an angular interceptor to add the authorization header for subsequent requests: 3)添加角度拦截器以为后续请求添加授权头:

 //...your interceptor
 return {
    'request': function (config) {

        // Get Current JWT
        var cookieToken = $cookieStore.get('currentToken');

        // If Authed, Tack on Auth Token
        if (cookieToken) {
            config.headers['Authorization'] = 'Bearer: ' + cookieToken;
        }

        return config || $q.when(config);
    }
}
//...remainder of interceptor

4) Adding middleware to verify users by token 4)添加中间件以通过令牌验证用户

public function handle($request, \Closure $next)
{
    if (! $token = $this->auth->setRequest($request)->getToken()) {
        return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
    }

    try {
        $user = $this->auth->authenticate($token);
    } catch (TokenExpiredException $e) {
        return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
    } catch (JWTException $e) {
        return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
    }

    if (! $user) {
        return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
    }

    return $next($request);
}

important to note that this code will not work for you as is, and was simply meant to show you what an implementation might look like 重要的是要注意,这段代码不适合你,而只是为了向你展示一个实现可能是什么样子

The full working implementation of this is way outside of a stackoverflow answer and I suggest reading into this elsewhere online. 这完全有效的实现方式超出了stackoverflow的答案,我建议在网上其他地方阅读。

If both sites are Laravel applications then you may needs just adjust the cookie domain in your config. 如果两个站点都是Laravel应用程序,那么您可能只需要在配置中调整cookie域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ajax请求来自不同域的Restful API - Ajax request to restful api from different domain 除了从Loopback Restful API登录外,无法获取或发布任何内容 - Cannot get or post anything besides login from loopback restful api 来自其他域和计算机的Web API发布 - Web API Post from other domain and computers 节点中用于反应应用程序的 Restful api - Restful api in node for react application Node js的RESTFUL API是否可以从其服务器托管在aws中的godaddy中的子域路由 - Can RESTFUL API of Node js routed from a sub domain in godaddy which has its server hosted in aws 针对静态API的角度登录/身份验证 - Angular login/authentication against restful API RESTful API-处理依赖于其他更新的更新 - RESTful API - handling updates that depend on other updates 当我无权修改其他域API时,如何从Javascript客户端向API发出跨域请求? - How to make Cross Domain Request to an API from Javascript Client when I don't have access to modify the other domain API? Electron Restful Api 没有反应或任何其他表达 - Electron Restful Api Without react or any other express 从AngularJs调用Restful api函数 - Calling Restful api function from AngularJs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM