-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 83ba1e7
Showing
61 changed files
with
8,882 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
.idea/ | ||
.vscode/ | ||
vendor/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
linters-settings: | ||
gocyclo: | ||
min-complexity: 25 | ||
goconst: | ||
min-len: 2 | ||
min-occurrences: 2 | ||
misspell: | ||
locale: US | ||
lll: | ||
line-length: 140 | ||
goimports: | ||
local-prefixes: github.com/acronis/go-authkit/ | ||
gocritic: | ||
enabled-tags: | ||
- diagnostic | ||
- performance | ||
- style | ||
- experimental | ||
disabled-checks: | ||
- whyNoLint | ||
- paramTypeCombine | ||
- sloppyReassign | ||
settings: | ||
hugeParam: | ||
sizeThreshold: 256 | ||
rangeValCopy: | ||
sizeThreshold: 256 | ||
funlen: | ||
lines: 120 | ||
statements: 60 | ||
|
||
linters: | ||
disable-all: true | ||
enable: | ||
- bodyclose | ||
- dogsled | ||
- errcheck | ||
- exportloopref | ||
- funlen | ||
- gochecknoinits | ||
- goconst | ||
- gocritic | ||
- gocyclo | ||
- gofmt | ||
- goimports | ||
- gosec | ||
- gosimple | ||
- govet | ||
- ineffassign | ||
- lll | ||
- misspell | ||
- nakedret | ||
- staticcheck | ||
- stylecheck | ||
- typecheck | ||
- unconvert | ||
- unparam | ||
- unused | ||
- whitespace | ||
|
||
issues: | ||
# Don't use default excluding to be sure all exported things (method, functions, consts and so on) have comments. | ||
exclude-use-default: false | ||
exclude-rules: | ||
- path: _test\.go | ||
linters: | ||
- dogsled | ||
- ineffassign | ||
- funlen | ||
- gocritic | ||
- gocyclo | ||
- gosec | ||
- goconst | ||
- govet | ||
- lll | ||
- staticcheck | ||
- unused | ||
- unparam |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
exclude: | ||
- message: Exclude values in test files and primitives for testing | ||
paths: | ||
- idptest/jwks_handler.go | ||
- jwt/jwt_test.go | ||
|
||
- message: Skip false positive high-entropy sequences | ||
id: high-entropy | ||
pattern: cfgKeyIntrospectionGRPCTLSEnabled |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
* @vasayxtx @MikeYast |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright © 2024 Acronis International GmbH. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
# Simple library in Go with primitives for performing authentication and authorization | ||
|
||
The library includes the following packages: | ||
+ `auth` (root directory) - provides authentication and authorization primitives for using on the server side. | ||
+ `jwt` - provides parser for JSON Web Tokens (JWT). | ||
+ `jwks` - provides a client for fetching and caching JSON Web Key Sets (JWKS). | ||
+ `idptoken` - provides a client for fetching and caching Access Tokens from Identity Providers (IDP). | ||
+ `idptest` - provides primitives for testing IDP clients. | ||
|
||
## Examples | ||
|
||
### Authenticating requests with JWT tokens | ||
|
||
The `JWTAuthMiddleware` function creates a middleware that authenticates requests with JWT tokens. | ||
|
||
It uses the `JWTParser` to parse and validate JWT. | ||
`JWTParser` can verify JWT tokens signed with RSA (RS256, RS384, RS512) algorithms for now. | ||
It performs <issuer_url>/.well-known/openid-configuration request to get the JWKS URL ("jwks_uri" field) and fetches JWKS from there. | ||
For other algorithms `jwt.SignAlgUnknownError` error will be returned. | ||
The `JWTParser` can be created with the `NewJWTParser` function or with the `NewJWTParserWithCachingJWKS` function. | ||
The last one is recommended for production use because it caches public keys (JWKS) that are used for verifying JWT tokens. | ||
|
||
See `Config` struct for more customization options. | ||
|
||
Example: | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/acronis/go-appkit/log" | ||
"github.com/acronis/go-authkit" | ||
) | ||
|
||
func main() { | ||
jwtConfig := auth.JWTConfig{ | ||
TrustedIssuerURLs: []string{"https://my-idp.com"}, | ||
//TrustedIssuers: map[string]string{"my-idp": "https://my-idp.com"}, // Use TrustedIssuers if you have a custom issuer name. | ||
} | ||
jwtParser, _ := auth.NewJWTParserWithCachingJWKS(&auth.Config{JWT: jwtConfig}, log.NewDisabledLogger()) | ||
authN := auth.JWTAuthMiddleware("MyService", jwtParser) | ||
|
||
srvMux := http.NewServeMux() | ||
srvMux.Handle("/", http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { | ||
_, _ = rw.Write([]byte("Hello, World!")) | ||
})) | ||
srvMux.Handle("/admin", authN(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { | ||
//jwtClaims := GetJWTClaimsFromContext(r.Context()) // GetJWTClaimsFromContext is a helper function to get JWT claims from context. | ||
_, _ = rw.Write([]byte("Hello, admin!")) | ||
}))) | ||
|
||
_ = http.ListenAndServe(":8080", srvMux) | ||
} | ||
``` | ||
|
||
```shell | ||
$ curl -w "\nHTTP code: %{http_code}\n" localhost:8080 | ||
Hello, World! | ||
HTTP code: 200 | ||
|
||
$ curl -w "\nHTTP code: %{http_code}\n" localhost:8080/admin | ||
{"error":{"domain":"MyService","code":"bearerTokenMissing","message":"Authorization bearer token is missing."}} | ||
HTTP code: 401 | ||
``` | ||
|
||
### Authorizing requests with JWT tokens | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/acronis/go-appkit/log" | ||
"github.com/acronis/go-authkit" | ||
) | ||
|
||
func main() { | ||
jwtConfig := auth.JWTConfig{TrustedIssuers: map[string]string{"my-idp": idpURL}} | ||
jwtParser, _ := auth.NewJWTParserWithCachingJWKS(&auth.Config{JWT: jwtConfig}, log.NewDisabledLogger()) | ||
authOnlyAdmin := auth.JWTAuthMiddlewareWithVerifyAccess("MyService", jwtParser, | ||
auth.NewVerifyAccessByRolesInJWT(Role{Namespace: "my-service", Name: "admin"})) | ||
|
||
srvMux := http.NewServeMux() | ||
srvMux.Handle("/", http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { | ||
_, _ = rw.Write([]byte("Hello, World!")) | ||
})) | ||
srvMux.Handle("/admin", authOnlyAdmin(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { | ||
_, _ = rw.Write([]byte("Hello, admin!")) | ||
}))) | ||
|
||
_ = http.ListenAndServe(":8080", srvMux) | ||
} | ||
``` | ||
|
||
Please see [example_test.go](./example_test.go) for a full version of the example. | ||
|
||
### Fetching and caching Access Tokens from Identity Providers | ||
|
||
The `idptoken.Provider` object is used to fetch and cache Access Tokens from Identity Providers (IDP). | ||
|
||
Example: | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"log" | ||
"net/http" | ||
|
||
"github.com/acronis/go-authkit/idptoken" | ||
) | ||
|
||
func main() { | ||
// ... | ||
httpClient := &http.Client{Timeout: 30 * time.Second} | ||
source := idptoken.Source{ | ||
URL: idpURL, | ||
ClientID: clientID, | ||
ClientSecret: clientSecret, | ||
} | ||
provider := idptoken.NewProvider(httpClient, source) | ||
accessToken, err := provider.GetToken() | ||
if err != nil { | ||
log.Fatalf("failed to get access token: %v", err) | ||
} | ||
// ... | ||
} | ||
``` | ||
|
||
## License | ||
|
||
Copyright © 2024 Acronis International GmbH. | ||
|
||
Licensed under [MIT License](./LICENSE). |
Oops, something went wrong.