繁体   English   中英

使用承载授权的本地策略的 Nuxt Auth 自定义方案

[英]Nuxt Auth Custom Scheme with local strategies using Bearer Authorization

我想使用本地策略制作自定义方案,但我不知道如何使用 customScheme 来实现。 nuxt/auth v5 的文档对我没有帮助

我想执行两个端点:

第一个请求

POST /oauth/v2/token
HEAD: 
  Content-Type: application/x-www-form-urlencoded

请求正文:

clientId : string
clientSecret: string
grantType: string
username: string
password: string

回复:

{
  "accessToken": "string",
  "expireTime": "2022-01-10T20:29:10.721Z",
  "refreshToken": "string"
}

第二次请求

GET /security/users/me
HEAD 
  x-locale: fr|en
  authorization: Bearer <TOKEN>

回复:

{
  "username": "string",
  "firstname": "string",
  "lastname": "string",
  "email": "string",
  "phone": "string",
  "locale": "fr",
  "id": 1,
  "enabled": true,
  "createdAt": "2022-01-10T20:38:36.478Z",
  "updatedAt": "2022-01-10T20:38:36.478Z",
  "expiresAt": "2022-01-10T20:38:36.478Z",
  "loggedAt": "2022-01-10T20:38:36.478Z",
  "roles": [
    {
      "name": "string",
      "description": "string",
      "code": "string",
      "id": 1,
      "enabled": true,
      "createdAt": "2022-01-10T20:38:36.478Z",
      "updatedAt": "2022-01-10T20:38:36.478Z",
      "translations": {
        "fr": {
          "name": "string",
          "description": "string"
        },
        "en": {
          "name": "string",
          "description": "string"
        }
      },
      "permissions": [
        {
          "id": 1,
          "code": "string",
          "endUI": {
            "name": "string",
            "title": "string",
            "id": 1,
            "code": "string",
            "type": {
              "name": "string",
              "code": "string",
              "id": 1,
              "enabled": true,
              "createdAt": "2022-01-10T20:38:36.478Z",
              "updatedAt": "2022-01-10T20:38:36.478Z",
              "translations": {
                "fr": {
                  "name": "string"
                },
                "en": {
                  "name": "string"
                }
              }
            },
            "module": {
              "name": "string",
              "description": "string",
              "code": "string",
              "id": 1,
              "enabled": true,
              "createdAt": "2022-01-10T20:38:36.478Z",
              "updatedAt": "2022-01-10T20:38:36.478Z",
              "translations": {
                "fr": {
                  "name": "string",
                  "description": "string"
                },
                "en": {
                  "name": "string",
                  "description": "string"
                }
              }
            },
            "icon": "string",
            "uri": "string",
            "translations": {
              "fr": {
                "name": "string",
                "title": "string"
              },
              "en": {
                "name": "string",
                "title": "string"
              }
            }
          }
        }
      ]
    }
  ],
  "avatar": {
    "id": 1,
    "url": "string"
  }
}

nuxt.config.js

    modules: [
        // https://go.nuxtjs.dev/axios
        '@nuxtjs/axios',
        // https://go.nuxtjs.dev/pwa
        '@nuxtjs/pwa',

        '@nuxtjs/auth-next',

        '@nuxtjs/dotenv',

        '@nuxtjs/i18n', [
            'nuxt-vuex-localstorage',
            {
                mode: 'debug',
                localStorage: [
                    'user',
                    'service',
                    'location',
                    'storeType',
                    'warehouse',
                    'openingRange',
                    'store',
                    'holiday',
                    'taxon',
                    'provider',
                    'productOption',
                    'productAttribute',
                    'product',
                    'productVariant',
                    'glassesCatalog'
                ],
            },
        ],
    ],
router: {
        middleware: ['auth']
    },
    // Auth Strategies
    auth: {
        strategies: {
            customStrategy: {
            _scheme: '~/schemes/customScheme',
            endpoints: {
                login: { 
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded' 
                }, 
                url: '/oauth/v2/token', 
                method: 'post' 
                },
                user: { 
                url: '/security/users/me', 
                method: 'get',
                propertyName: '',
                headers: {
                    'x-locale': 'fr',
                    'Authorization': `Bearer ${It should be a token (accessToken) for the first request}`
                }                 
                }
            }
            }
        }
    }

~/schemes/customeScheme.js


import { LocalScheme } from '~auth/runtime'

export default class CustomScheme extends LocalScheme {
  // Override `fetchUser` method of `local` scheme
  async fetchUser (endpoint) {
    // Token is required but not available
    if (!this.check().valid) {
      return
    }

    // User endpoint is disabled.
    if (!this.options.endpoints.user) {
      this.$auth.setUser({})
      return
    }
    
    // Try to fetch user and then set
    return this.$auth.requestWith(
      this.name,
      endpoint,
      this.options.endpoints.user
    ).then((response) => {
      const user = getProp(response.data, this.options.user.property)
      
      // Transform the user object
      const customUser = {
        ...user,
        fullName: user.firstName + ' ' + user.lastName,
        roles: ['user']
      }
      
      // Set the custom user
      // The `customUser` object will be accessible through `this.$auth.user`
      // Like `this.$auth.user.fullName` or `this.$auth.user.roles`
      this.$auth.setUser(customUser)

      return response
    }).catch((error) => {
      this.$auth.callOnError(error, { method: 'fetchUser' })
    })
  }
}

~/login.vue

onSubmit(){
      this.isSubmitting = true;
      this.isDisabled= true;
      let formData = new FormData();
      formData.append("clientId", process.env.CLIENT_ID);
      formData.append("clientSecret", process.env.CLIENT_SECRET);
      formData.append("grantType", "password");
      formData.append("username", this.dataUser.username);
      formData.append("password", this.dataUser.password);

      this.$refs.dataUser.validate(async (valid, fieldsError) => {
         this.validate = valid; 
         if(valid){
            try {
            let response =  await this.$auth.loginWith('customStrategy', { data: formData })
            console.log(response);
            this.$store.dispatch('storeSecurity/storeUserToken', response.data);
          } catch (error) {
            this.$message.error({content: this.$t("login.error"), key, duration: 3}); 
                        
          }
        }
      });
    },

如果我想获取用户,我该怎么做??? 我所做的一切都给了我在文档中没有答案的错误

我需要帮助

您应该在成功登录后使用$auth.setUser(user)设置当前用户。 那就是如果您的endpoints.user不起作用。

暂无
暂无

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

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