【问题标题】:Get to work with the authenticated guard in laravel API在 laravel API 中使用经过身份验证的守卫
【发布时间】:2018-11-21 12:46:54
【问题描述】:

我有几个警卫的会话登录系统。我经常使用 Vue,我需要在 Vue 中进行身份验证才能正确获取和发布数据。问题是如何让经过身份验证的会话用户使用 API。所以在 api.php 我想使用一个控制器,其中间件是经过身份验证的用户。我不想使用 Passport,因为我只能通过网页登录,而不是 API。

【问题讨论】:

    标签: php laravel api authentication laravel-middleware


    【解决方案1】:

    vue 支持组件还有一些叫做 props 的东西,它们是可以传递给 vue 组件的数据,我通常会做的是将经过身份验证的用户 ID 传递给我的 vue 组件,然后当我从 vue 组件发出请求时我会将当前经过身份验证的用户传递到后端,并在那里检查通过请求接收到的 id 是否与当前经过身份验证的用户相同。

    查看下面的示例,我将使用常规守卫

    从刀片加载 vue 组件

    //loading vue test-component and pass the authenticated user 
    <test-component :authuser="{{Auth::(user)->id}}"></test-component>
    

    vue 组件

    <script>
    export default {
        props : ['authuser'], //should be the same name as you passed it
        data(){
            return {
    
            }
        },
        created(){
            axios.post('/api/test' , {
                 'authuser' : this.authuser
            })
            .then(res => {
                console.log(res);
            })
            .catch(err => {
    
            });
        }
    }
    

    API 路由

    use Auth;
    
    Route::post('api/test' , function($request){
        if(Auth::user()->id == $request->authuser)
           return 'you are authenticated';
        else 
           return 'you are not authenticated';
    });
    

    希望对您有所帮助,祝您好运。

    【讨论】:

    • 哦,这是一个很好的例子,感谢您的努力!虽然这不是我想要的。在我的控制器中,我应该使用中间件,这样我就无法获得当前经过身份验证的守卫。我正在使用Hesto/multi-auth 每当我设置构造函数时,我都会收到未经身份验证的错误,即使我在构造函数中设置了特定的保护
    • 在这种情况下,您很受欢迎授权方法中的类,您可以在那里使用 Auth 门面尝试
    猜你喜欢
    • 2016-09-26
    • 2021-05-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多