简体   繁体   中英

RESTful Laravel API login from application in other domain

How to config Laravel 5.0 to login from other domain? Explain, we have a Laravel RESTful API, and some users creates Angular.js apps and host on your own domains.

When try to login through these apps, login returns true, but on next request lose the session.

I think that can be related to CORS, but I set the correct headers.

My Headers:

Hearders setted on apache virtualhost:

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. 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. You should look into using a JWT library.

laravel-jwt is pretty solid for accomplishing this. Simply adding CORS into your app won't be enough for it to work properly.

Laravel needs to know what user is making the request and the above library comes with middleware and methods to easily accomplish this.

From a high level, some of the steps that will need to occur are:

1) Setting up your angular login controller/service

    $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:

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:

 //...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

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.

If both sites are Laravel applications then you may needs just adjust the cookie domain in your config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM