编写oauth controller代码:

package controllersimport ("encoding/json""fmt""errors""alertmanager/models""alertmanager/utils/oauth""github.com/astaxie/beego""github.com/astaxie/beego/orm""github.com/astaxie/beego/session"
)type OAuthController struct {BaseController
}var globalSessions *session.Managerfunc init() {sessionConfig := &session.ManagerConfig{CookieName:      "gosessionid",EnableSetCookie: true,Gclifetime:      3600,Maxlifetime:     3600,Secure:          false,CookieLifeTime:  3600,ProviderConfig:  "./tmp",}globalSessions, _ = session.NewManager("memory", sessionConfig)go globalSessions.GC()
}func (c *OAuthController ) OAuthUrl() {data := map[string]interface{}{"oauthUrl": oauth.GetOauthUrl()}c.HandleResult(&data)
}func (c *OAuthController ) Login() {code := c.GetString(":code")token, err := oauth.GetAccessToken(code)if err != nil {c.HandleError(err)}user, err := oauth.GetUserInfo(token.AccessToken)if err != nil {c.HandleError(err)}c.SetSession("user", user)data := map[string]interface{}{"user": user}c.HandleResult(&data)
}func (c *OAuthController ) Validate() {user := c.GetSession("user")if user == nil {err := fmt.Errorf("%s", "not login")c.HandleError(err)} else {data := map[string]interface{}{"user": user,}c.HandleResult(&data)}
}func (c *OAuthController ) Logout() {c.DelSession("user")c.HandleResult(nil)
}func (c *OAuthController ) NofityInsertUser() {b := c.Ctx.Input.RequestBodyvar user models.AlertUsererr := json.Unmarshal(b, &user)if err != nil {beego.Error(err)c.HandleError(err)return}// TODOo := orm.NewOrm()_, err = o.Insert(&user)if err != nil {beego.Error(err)c.HandleError(err)return}beego.Info(user)c.HandleResult(nil)
}func (c *OAuthController ) BackAdminLogin () {code := c.GetString(":admin")if code == "k8spaas" {var user oauth.Useruser.Name = "admin"user.Role.Name = "admin"c.SetSession("user", user)data := map[string]interface{}{"user": user}c.HandleResult(&data)return}var err_back error = errors.New("error admin password.")c.HandleError(err_back)
}

utils/oauth:

package oauthimport ("encoding/json""fmt""net/url""github.com/astaxie/beego""github.com/parnurzeal/gorequest"
)var (serverUrl         stringserverRedirectUrl stringauthorizePath     stringtokenPath         stringuserInfoPath      stringuserListPath      stringresponseType      stringscope             stringclientId          stringclientSecret      stringgrantType         stringredirectUri       stringoauthUrl          stringrawTokenUrl       stringuserInfoUrl       stringuserListUrl       string
)func init() {serverUrl = beego.AppConfig.String("oauth.server.server_url")serverRedirectUrl = beego.AppConfig.String("oauth.server.redirect_url")authorizePath = beego.AppConfig.String("oauth.path.authorize")tokenPath = beego.AppConfig.String("oauth.path.token")userInfoPath = beego.AppConfig.String("oauth.path.user.info")userListPath = beego.AppConfig.String("oauth.path.user.list")responseType = beego.AppConfig.String("oauth.response_type")scope = beego.AppConfig.String("oauth.scope")clientId = beego.AppConfig.String("oauth.client_id")clientSecret = beego.AppConfig.String("oauth.client_secret")grantType = beego.AppConfig.String("oauth.grant_type")redirectUri = beego.AppConfig.String("oauth.redirect_uri")oauthUrl = serverRedirectUrl + authorizePath +"?response_type=" + responseType +"&scope=" + scope +"&client_id=" + clientId +"&redirect_uri=" + url.QueryEscape(redirectUri)rawTokenUrl = serverUrl + tokenPath +"?client_id=" + clientId +"&client_secret=" + clientSecret +"&grant_type=" + grantType +"&redirect_uri=" + url.QueryEscape(redirectUri)userInfoUrl = serverUrl + userInfoPathuserListUrl = serverUrl + userListPath}func GetOauthUrl() string {return oauthUrl
}func GetUserInfo(accessToken string) (User, error) {beego.Info("oauth2.GetUserInfo begin.")request := gorequest.New()var user User_, body, errs := request.Get(userInfoUrl).Set("Authorization", "Bearer "+accessToken).End()if errs != nil {beego.Error(errs[0])return user, errs[0]}fmt.Println(body)err := json.Unmarshal([]byte(body), &user)return user, err
}func GetAccessToken(code string) (OauthAccessToken, error) {beego.Info("oauth2.GetAccessToken begin.")tokenUrl := GetTokenUrl(code)request := gorequest.New()var token OauthAccessToken_, body, errs := request.Post(tokenUrl).Set("Accept", "application/json").End()if errs != nil {beego.Error(errs[0])return token, errs[0]}fmt.Println(body)err := json.Unmarshal([]byte(body), &token)return token, err
}func GetTokenUrl(code string) string {return rawTokenUrl + "&code=" + code
}

types:

package oauthtype OauthAccessToken struct {AccessToken  string `json:"access_token"`TokenType    string `json:"token_type"`RefreshToken string `json:"refresh_token"`ExpiresIn    int    `json:"expires_in"`Scope        string `json:"scope"`
}type Role struct {Name string `json:"name"`
}type User struct {Id    int    `json:"id"`Name  string `json:"name"`Email string `json:"email"`Phone string `json:"phone"`Role  Role   `json:"role"`
}

配置文件:

sessionon = true
oauth.path.token = /oauth/token
oauth.path.authorize = /oauth/authorize
oauth.path.user.info = /user/info
oauth.path.user.list = /user/info/list
oauth.client_id= curl-client
oauth.client_secret= client-secret
oauth.grant_type= authorization_code
oauth.response_type= code
oauth.scope= read write[dev]oauth.server.server_url = http://oauth2.abc.sheincorp.cn
oauth.server.redirect_url = http://oauth2.abc.sheincorp.cn
oauth.redirect_uri = http://localhost:8082/#/OAuth

一定要设置sesstionon = true, 否则调用GetSession() SetSesstion() 方法会有异常。

异常如下:

Handler crashed with error runtime error: invalid memory address or nil pointer dereference

beego 使用github.com/astaxie/beego/session异常问题相关推荐

  1. Go报错package github.com/astaxie/beego: exit status 128

    问题 # cd .; git clone https://github.com/astaxie/beego /www/project/src/github.com/astaxie/beego Init ...

  2. table: github.com/astaxie/beego/orm.Ormer not found

    报错: table: github.com/astaxie/beego/orm.Ormer not found, make sure it was registered with RegisterMo ...

  3. 【Go】go get -u github.com/astaxie/beego没有反应

    一.报错 博主是Go新手,最近开始学习beego框架,使用 "go get -u github.com/astaxie/beego" 命令下载beego框架时长时间没有反应,最后报 ...

  4. [Go] 解决main.go:5:2: missing go.sum entry for module providing package github.com/astaxie/beego

    当在代码中使用了第三方库 ,但是go.mod中并没有跟着更新的时候 如果直接run或者build就会报这个错误 main.go:5:2: missing go.sum entry for module ...

  5. go get github.com/astaxie/beego 没有反应

    因为网速较慢导致的... 下面是我设置的hosts,各位童鞋可以用IP查找工具来获取IP地址设置hosts,速度1-2分钟可以下载结束. 在host 文件中设置: 192.30.253.112 git ...

  6. missing go.sum entry for module providing package github.com/astaxie/beego

    解决方法 //执行如下代码 go build -mod=mod

  7. beego model获取controller_Goweb开发-Beego框架实战教程:项目搭建及注册用户

    一.搭建项目 首先打开终端进入gopath下的src目录,然后执行以下命令,创建一个beego项目: bee new myblogweb 运行效果如下: 然后通过goland打开该项目: 我们打开co ...

  8. beego原生mysql查询_go——beego的数据库增删改查

    一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...

  9. Spring boot 解决 hibernate no session异常

    Spring boot 解决 hibernate no session异常 参考文章: (1)Spring boot 解决 hibernate no session异常 (2)https://www. ...

最新文章

  1. 开发微信小程序入门前
  2. GitHub 总星 4w+!删库?女装?表情包?这些沙雕中文项目真是我每天快乐的源泉!...
  3. Visual C++ MFC/ATL开发-高级篇(一)
  4. 使用bc45编译ucos-II的配置过程
  5. 日志库EasyLogging++学习系列(2)—— 日志级别
  6. 一切为了高清——金山云魔镜平台助推5G高清应用
  7. ad10怎么挖铺的铜_黄金怎么验真假,简单易行方法多。
  8. OpenCV3学习(7.4)——图像分割之四(Meanshift算法,PyrMeanShiftFiltering函数)
  9. OKR与影响地图,别再傻傻分不清
  10. Java基础知识强化84:System类之exit()方法和currentTimeMillis()方法
  11. Android原生支持组件编译,从0开始编译android类原生系统
  12. 电路交换、报文交换、分组交换各自的特点
  13. Vue搭脚手架及创建项目
  14. dorado java_dorado事件
  15. ArcEngine中的ICommand接口和ITool接口
  16. mac如何看html5视频播放器,适用于Mac的HTML5视频播放器
  17. android intent传文件,android如何用intent跳转到文件管理器
  18. JAVA里的空白\t\n\r分别代表什么?
  19. Kotlin Flow 背压和线程切换竟然如此相似
  20. 监听audio是否加载完毕

热门文章

  1. 命令行中只用scala来运行一个spark应用
  2. ubuntu16.04下面的redis desktop manger的使用
  3. 阿里云ECS在CentOS 6.9中使用Nginx提示:nginx: [emerg] socket() [::]:80 failed (97: Address family not supported
  4. 针对eclipse调式代码时打断点出现斜杠的解决方法
  5. Base64加密---加密学习笔记(一)
  6. 微信分享接口示例(设置标题、缩略图、连接、描述),附demo下载
  7. BZOJ 2566 xmastree(树分治+multiset)
  8. 【Go】Panic函数
  9. Python面向对象2-类和构造方法
  10. Spring RestTemplate中几种常见的请求方式GET请求 POST请求 PUT请求 DELETE请求