Golang中Iris框架与OAuth2集成及Vue.js前端开发实战

Golang中Iris框架与OAuth2集成及Vue.js前端开发实战 我正在我的Web应用程序(使用Iris框架构建)中尝试通过API使用合适的OAuth2库。我希望使用自己的服务器进行身份验证……(授权类型应为资源所有者密码凭证),感谢任何推荐。

1 回复

更多关于Golang中Iris框架与OAuth2集成及Vue.js前端开发实战的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中使用Iris框架集成OAuth2时,推荐使用golang.org/x/oauth2标准库,它提供了完整的OAuth2客户端实现。对于资源所有者密码凭证授权类型,可以按以下方式配置:

首先安装依赖:

go get golang.org/x/oauth2

以下是完整的Iris集成示例:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/kataras/iris/v12"
	"golang.org/x/oauth2"
)

var (
	oauth2Config = &oauth2.Config{
		ClientID:     "your-client-id",
		ClientSecret: "your-client-secret",
		Endpoint: oauth2.Endpoint{
			TokenURL: "https://your-auth-server.com/oauth/token",
		},
		Scopes: []string{"read", "write"},
	}
)

type TokenRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func main() {
	app := iris.New()

	// OAuth2 token端点
	app.Post("/oauth/token", func(ctx iris.Context) {
		var req TokenRequest
		if err := ctx.ReadJSON(&req); err != nil {
			ctx.StatusCode(iris.StatusBadRequest)
			ctx.JSON(iris.Map{"error": "invalid request"})
			return
		}

		// 使用密码凭证授权获取token
		token, err := oauth2Config.PasswordCredentialsToken(context.Background(), req.Username, req.Password)
		if err != nil {
			ctx.StatusCode(iris.StatusUnauthorized)
			ctx.JSON(iris.Map{"error": "authentication failed"})
			return
		}

		ctx.JSON(iris.Map{
			"access_token":  token.AccessToken,
			"token_type":    token.TokenType,
			"refresh_token": token.RefreshToken,
			"expires_in":    int64(token.Expiry.Sub(token.Expiry).Seconds()),
		})
	})

	// 受保护API端点示例
	app.Get("/api/protected", authenticateMiddleware, func(ctx iris.Context) {
		userID := ctx.Values().GetString("user_id")
		ctx.JSON(iris.Map{
			"message": fmt.Sprintf("Hello user %s", userID),
			"status":  "success",
		})
	})

	app.Listen(":8080")
}

// 认证中间件
func authenticateMiddleware(ctx iris.Context) {
	authHeader := ctx.GetHeader("Authorization")
	if authHeader == "" {
		ctx.StatusCode(iris.StatusUnauthorized)
		ctx.JSON(iris.Map{"error": "missing authorization header"})
		return
	}

	// 验证token逻辑(这里需要实现具体的token验证)
	token := authHeader[len("Bearer "):]
	userID, err := validateToken(token)
	if err != nil {
		ctx.StatusCode(iris.StatusUnauthorized)
		ctx.JSON(iris.Map{"error": "invalid token"})
		return
	}

	ctx.Values().Set("user_id", userID)
	ctx.Next()
}

// Token验证函数(需要根据你的认证服务器实现)
func validateToken(token string) (string, error) {
	// 这里应该调用你的认证服务器验证token
	// 示例实现 - 实际使用时需要替换为真实的验证逻辑
	client := oauth2Config.Client(context.Background(), &oauth2.Token{AccessToken: token})
	resp, err := client.Get("https://your-auth-server.com/userinfo")
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	var userInfo struct {
		UserID string `json:"user_id"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
		return "", err
	}

	return userInfo.UserID, nil
}

对于Vue.js前端,可以使用axios进行API调用:

// Vue.js组件示例
<template>
  <div>
    <input v-model="username" placeholder="Username">
    <input v-model="password" type="password" placeholder="Password">
    <button @click="login">Login</button>
    <button @click="fetchProtectedData" :disabled="!accessToken">Get Protected Data</button>
    <div v-if="protectedData">{{ protectedData }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      accessToken: '',
      protectedData: null
    }
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/oauth/token', {
          username: this.username,
          password: this.password
        });
        
        this.accessToken = response.data.access_token;
        localStorage.setItem('access_token', this.accessToken);
      } catch (error) {
        console.error('Login failed:', error);
      }
    },
    
    async fetchProtectedData() {
      try {
        const response = await axios.get('/api/protected', {
          headers: {
            'Authorization': `Bearer ${this.accessToken}`
          }
        });
        
        this.protectedData = response.data;
      } catch (error) {
        console.error('Failed to fetch protected data:', error);
      }
    }
  },
  
  mounted() {
    const token = localStorage.getItem('access_token');
    if (token) {
      this.accessToken = token;
    }
  }
}
</script>

这个实现提供了完整的OAuth2密码凭证授权流程,包括token获取、验证和保护API端点。你需要根据实际的认证服务器调整token验证逻辑和端点配置。

回到顶部