1. Register ali Cloud and open OSS service

Slightly 😛

2. Upload files directly to the OSS on the WEB

2-1. Use STS temporary authorization to allow the WEB side to directly access OSS

1. Some users may need to directly access OSS resources.

2. For these users, only a temporary access certificate needs to be generated (ali Cloud STS service provides temporary access permission management for Ali Cloud accounts (or RAM users).) You do not need to worry about permission revocation. The temporary access certificate will automatically become invalid after it expires.

4. Temporary access credentials generated through STS include SecurityToken (SecurityToken) STS AK (AccessKeyId and AccessKeySecret)

5. Using the AccessKey method is the same as when you send a request using the AccessKey of Ali Cloud account or RAM user. It is important to note that security tokens must be carried in every request to OSS.

More detailed introduction: Ali Cloud User

2-2. Configure the OSS storage bucket

Create a Bucket named blog-userdata to store userdata.

Go to Bucket -> Permission Management – Cross domain Settings

Configured to

Source: Set this parameter to *. Allow Methods: Select GET, POST, PUT, DELETE, and HEAD. Allow Headers: set to *. Expose Headers: Set it to ETag, X-OSs-request-id, or X-oss-version-id.Copy the code

2-3. Configure RAM access control

1. Create an Aliyun sub-account.

Log in to RAM console with cloud account. In the left navigation bar, click Users under the People Management menu. Click Create user.

  1. Enter a login name and display name.
  2. Under the Access Mode area, select Programmatic access.
  3. Click OK, and then click Copy to save the access keys (AccessKeyId and AccessKeySecret).
  4. Select the created subaccount and click Add Permission.
  5. In the add permissions page, add AliyunSTSAssumeRoleAccess permissions for account has been created.
  6. Click OK.

2. Create a permission policy.

  1. In the navigation tree on the left, click Permission Policy Management.

  2. Click To create a permission policy.

  3. Enter the policy name and remarks.

  4. Configuration mode Select script configuration

Add the ListObjects, PutObject, and GetObject permissions to ossUsers. The following is an example of the configuration script in the policy content:

{
    "Version": "1"."Statement": [{"Effect": "Allow"."Action": [
             "oss:ListObjects"."oss:PutObject"."oss:AbortMultipartUpload"."oss:GetObject"]."Resource": [
             "acs:oss:*:*:blog-userdata"."acs:oss:*:*:blog-userdata/*"]]}}Copy the code

3. Create roles and assign rights policies

  1. In the left navigation bar, click RAM Role Management.
  2. Click Create RAM role, select the trusted entity type as Ali Cloud account, and click Next.
  3. On the Page for Creating a RAM role, enter the RAM role name and remarks.
  4. Select the cloud account as the current cloud account.
  5. Click Finish, and then click Authorize the role.
  6. On the Add Permission page, select user-defined permission policies and add the permission policies created in Step 2.
  7. Get the characterARNFor example,acs:ram::13**********623:role/ramosstest

So far, we have created an Ali Cloud sub-account, created the permission policy of OSS(blog- Userdata), created a role and allocated the permission policy of OSS(blog- Userdata), and obtained the ARN of this role.

If you do not understand this step, you are advised to read the official documentation carefully and practice several times 😄

3. Implementation of Eggjs server interface

3-1. Build the Eggjs project

Slightly 😛

No, see my previous article implementing RESTful apis with Eggjs

3-2. Implement TST authorization interface

1. The installation depends on NPM install@alicloud/STS-SDK

2. Set config parameters

// ./config/config.default.js

// STS - OSS
config.sts = {
  endpoint: 'sts.aliyuncs.com'.// In Mainland China, you can use the unified public network access address or the local access address.
  accessKeyId: 'LT************RVns'.// check this from aliyun console
  accessKeySecret: 'oPe*************4Wn'.// check this from aliyun console
};

Copy the code

3. Configure routes

// ./app/.router.js

// Cloud
router.get('/api/v1/ossToken', app.jwt, controller.cloud.getStsToken);
Copy the code

4.controller

// ./app/controller/cloud.js

'use strict';

const Controller = require('egg').Controller;

const getTokenRule = {
  accountID: { type: 'string'.required: true },
  roleName: { type: 'string'.required: true}};class CloudController extends Controller {
  async getStsToken() {
    const { ctx } = this;
    ctx.validate(getTokenRule, ctx.query);
    // Process logic
    const { code, body } = await ctx.service.cloud.getStsToken(ctx.query);
    // Return the response body and status code
    ctx.body = { ...body };
    ctx.status = code;
  }
}

module.exports = CloudController;


Copy the code

5.service

// ./app/service/cloud.js

'use strict';

const Service = require('egg').Service;
const StsClient = require('@alicloud/sts-sdk');

class CloudService extends Service {
  async getStsToken(query) {
    const { accountID, roleName } = query;
    const {
      endpoint,
      accessKeyId,
      accessKeySecret,
    } = this.config.sts;
    const sts = new StsClient({
      endpoint,
      accessKeyId,
      accessKeySecret,
    });
    /** * Sumerole (RoleArn,RoleSessionName) * RoleArn: ARN for the specified role. Format: acs:ram::$accountID:role/$roleName. * RoleSessionName: user-defined parameter. This parameter is used to distinguish between different tokens and can be used for user-level access auditing. * /
    const res1 = await sts.assumeRole(
      `acs:ram::${accountID}:role/${roleName}`.'client_web'
    );
    console.log(res1);
    if (res1.Credentials.SecurityToken) {
      const res2 = await sts.getCallerIdentity();
      console.log(res2);
      return { code: 200.body: { status: true.msg: 'Obtain success'.data: res1 } };
    }
    return { code: 500.body: { status: true.msg: 'Fetch failed'}}; }}module.exports = CloudService;


Copy the code

6. Access interface test

$ curl --location --request GET 'http://localhost:7001/api/v1/ossToken? accountID=1332314452386623&roleName=ramosstest' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZmMzNWI4YjZiYmI2ODMzNmU3NTEyYjgiLCJuYW1lIjoi55So5oi3NzE5NzM1Iiwic3RhdHV zIjoxMDAsImlhdCI6MTYwNjcyNDk1NCwiZXhwIjoxNjA2ODExMzU0fQ.5pxEeb39H8_RDyclMraKxSW4hSrFw6333f-qeCBuFYw'// return * to omit {"status": true."msg": "Get ahead"."data": {
        "SecurityToken": "CAIS8wF1q6Ft5B2yfSjIr**********dQMEUzFOG4Pw=="."AccessKeyId": "STS.NT7np***********36sLUaER"."AccessKeySecret": "C5rBieF**********4JnAm6rVYnvppEFqezw"."Expiration": "2020-11-31T04:53:23Z"}}Copy the code

4. Realization of uploading files through Web Vue

1. Install dependencies

npm install ali-oss --save

2. Simple demo

<template>
  <div>
    <button @click="getOssToken">Access token</button>
    <span>Uploading OSS files</span>
    <br />
    <input ref="file" type="file" id="uploadImage" @change="toUpload" />
    <br />{{imgUrl}}<img :src="imgUrl" />
  </div>
</template>
<script>
import OSS from 'ali-oss'
export default {
  data() {
    return {
      imgUrl: ' '.ossConfig: {
        accountID: '1332314452386623'.roleName: 'ramosstest'
      },
      ossParameter: {}}}.methods: {
    getOssToken() {
      this.axios
        .get('/api/v1/ossToken', {
          params: this.ossConfig
        })
        .then(res= > {
          this.ossParameter = res.data.data
          console.log(this.ossParameter)
        })
    },
    toUpload() {
      console.log('Ready to upload')
      const files = this.$refs.file.files[0]
      const name = files.name
      console.log(files)
      const client = new OSS({
        region: 'oss-cn-hangzhou'.accessKeyId: this.ossParameter.AccessKeyId,
        accessKeySecret: this.ossParameter.AccessKeySecret,
        bucket: 'blog-userdata'.stsToken: this.ossParameter.SecurityToken
      })
      console.log('Initialization completed')
      const that = this
      client
        .multipartUpload(name, files)
        .then(function(res) {
          const str = res.res.requestUrls[0]
          that.imgUrl = str.split('? ') [0]
          console.log('Upload successful! ', str.split('? ') [0])
        })
        .catch(err= > {
          console.log(err)
        })
    }
  }
}
</script>


Copy the code

3. Effect preview

Return to the upload address is: blog-userdata.oss-cn-hangzhou.aliyuncs.com/xinxiaomeng…

conclusion

⚠️ code is not strict enough, do not copy on production!

Novice easily wrong parameter configuration, please be sure to read the official document carefully.