GolangNote

Golang笔记

使用 OpenID Connect 简单而安全的授权应用程序

Permalink

OIDC 是一种使用 OpenID Connect(OIDC)协议授权应用程序的简单而安全的方法。OIDC 得到了大多数主要平台的支持,包括Okta、Google、Auth0、Keycloft、Authentik和其他平台。

它是OAuth 2.0协议之上的一个简单身份层,允许客户端根据授权服务器执行的身份验证来验证最终用户的身份。OIDC为客户端提供了对用户进行身份验证和获取基本用户配置文件信息的标准方法。

该库同时支持客户端凭据(M2M)和授权代码流(UI

用法

Go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main

import (
	"context"
	"flag"
	"fmt"
	oidclogin "github.com/reddec/oidc-login"
	"net/http"
)

func main() {
	var clientID, clientSecret, issuer string
	flag.StringVar(&clientID, "client-id", "", "Client ID")
	flag.StringVar(&clientSecret, "client-secret", "", "Client secret")
	flag.StringVar(&issuer, "issuer", "", "OIDC issuer URL")
	var binding string
	flag.StringVar(&binding, "bind", "127.0.0.1:8080", "HTTP server binding")
	flag.Parse()

	if clientID == "" || clientSecret == "" || issuer == "" {
		panic("all OIDC flags required")
	}

	auth, err := oidclogin.New(context.Background(), oidclogin.Config{
		IssuerURL:    issuer,
		ClientID:     clientID,
		ClientSecret: clientSecret,
	})
	if err != nil {
		panic(err) // handle it properly in production
	}

	// add secured route (or group)
	http.Handle("/", auth.SecureFunc(func(writer http.ResponseWriter, request *http.Request) {
		token := oidclogin.Token(request)
		name := oidclogin.User(token)
		writer.Header().Set("Content-Type", "text/html")
		_, _ = writer.Write([]byte("<html><body><h1>Hello, " + name + "</h1></body></html>"))
	}))

	// add callback prefixes
	http.Handle(oidclogin.Prefix, auth)

	// start
	fmt.Println("ready")
	_ = http.ListenAndServe(binding, nil)
}

本文网址: https://golangnote.com/topic/320.html 转摘请注明来源

Related articles

golang rot13 简单加密字符

ROT13 是一种简单的字符加密方法,把 26 个英文字母的前 13 个字母与后 13 个字母的编码互换。...

Write a Comment to "使用 OpenID Connect 简单而安全的授权应用程序"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms