package main import ( c "dsSso/Controller" "dsSso/Dao/DaoAppBase" "dsSso/Handler" "dsSso/Middleware" "dsSso/Utils" "dsSso/Utils/ConfigUtil" "dsSso/Utils/FileUtil" "dsSso/Utils/RedisStorage" "dsSso/Utils/RedisUtil" "fmt" "github.com/RangelReale/osin" "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" "time" //http://www.freesion.com/article/3571182257/ _ "dsSso/docs" ) /** 功能:启动OAuth2服务器 作者:黄海 时间:2020-03-25 */ func startOAuth2Server() { //清空Redis RedisUtil.FlushAll() //声明OAuth2的Redis存储器 RedisStorage.OAuth2RedisStorage = &RedisStorage.RedisStorage{ Pool: RedisUtil.Pool, KeyPrefix: ConfigUtil.OAuth2RedisKeyPrefix, } // 启动OAuth2的服务器 cfg := osin.NewServerConfig() cfg.AllowGetAccessRequest = true cfg.AllowClientSecretInParams = true cfg.AllowedAccessTypes = append(cfg.AllowedAccessTypes, osin.REFRESH_TOKEN) RedisStorage.OsinServer = osin.NewServer(cfg, RedisStorage.OAuth2RedisStorage) //这里需要循环从数据库中获取数据 list, _ := DaoAppBase.GetAppBaseListFromDb() for i := 0; i < len(list); i++ { appKey := list[i]["access_key"].(string) secret := list[i]["secret_key"].(string) redirectUri := list[i]["redirect_uri"].(string) RedisStorage.OAuth2RedisStorage.CreateClient( &osin.DefaultClient{ Id: appKey, Secret: secret, RedirectUri: redirectUri, }, ) } } // @title 东师理想统一认证中心(OAuth2+Sso) // @version 2.0 // @description 参考自xxl-sso // @host 127.0.0.1:8000 func main() { // 发布模式 //gin.SetMode(gin.ReleaseMode) // 开发模式 gin.SetMode(gin.DebugMode) // 开启gin服务器 r := gin.Default() //设置静态资源 r.Static("/sso/static", "./static") //启用日志中间件 r.Use(Middleware.LoggerToKafka()) // 允许跨域 r.Use(Utils.Cors()) // 显示Logo var logo = FileUtil.ReadFileContent("./Config/logo.txt") fmt.Print(logo) //注册swagger r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) //注册启动OAuth2服务器 startOAuth2Server() //开启一个协程,用于每1分钟更新一下REDIS中接入系统的信息 go SyncAppRedis() //注册登录验证拦截器 r.Use(Handler.AuthorizeHandler()) //主路由 c.GinRouter(r) // 监听并在 0.0.0.0:8000 上启动服务 r.Run(":" + ConfigUtil.ServerPort) } //每隔一分钟,对redis中的app接入系统数据进行重新加载 func SyncAppRedis() { list, _ := DaoAppBase.GetAppBaseListFromDb() for i := 0; i < len(list); i++ { appKey := list[i]["access_key"].(string) secret := list[i]["secret_key"].(string) redirectUri := list[i]["redirect_uri"].(string) RedisStorage.OAuth2RedisStorage.CreateClient( &osin.DefaultClient{ Id: appKey, Secret: secret, RedirectUri: redirectUri, }, ) } // 每1分钟执行一次 time.AfterFunc(1*time.Minute, SyncAppRedis) }