package saml import ( "bytes" "crypto/x509" "encoding/pem" "errors" "fmt" "os" "github.com/crewjam/saml" "github.com/phuslu/log" "gopkg.in/dgrijalva/jwt-go.v3" ) func initcert(file string, verify func(interface{}) bool) (key interface{}, err error) { var blocks []*pem.Block if file == "" { err = fmt.Errorf("File %s is empty", file) return } blocks, err = loadcerts(file) if err != nil { return nil, err } for _, b := range blocks { var key interface{} key, err = x509.ParsePKCS8PrivateKey(b.Bytes) if err != nil { key, err = x509.ParseCertificate(b.Bytes) if err != nil { log.Warn().AnErr("parsingerror", err).Msgf("could not parse file %s as publickey or as an privatekey", file) continue } } if key == nil { return nil, fmt.Errorf("Cannot find an Key in %s", file) } if verify(key) { return key, nil } } return nil, errors.New("No key found") } func loadcerts(filename string) (blocks []*pem.Block, err error) { var file *os.File if file, err = os.Open(filename); err != nil { return } var buffer bytes.Buffer read, err := buffer.ReadFrom(file) log.Debug().Int64("read bytes", read).Err(err).Msgf("Read file %s", filename) if err != nil { return } data := buffer.Bytes() var block *pem.Block for { if len(data) == 0 { return } block, data = pem.Decode(data) if block != nil { blocks = append(blocks, block) } } } func empty(data []string) bool { for _, t := range data { if t == "" { return true } } return false } func jwttoken(claim jwt.Claims, privatekey interface{}) (string, error) { token := jwt.NewWithClaims( jwt.SigningMethodPS512, claim, ) return token.SignedString(privatekey) } func attributeStatementstomap(a []saml.AttributeStatement) map[string][]string { var output = map[string][]string{} for _, b := range a { for _, c := range b.Attributes { if _, ok := output[c.FriendlyName]; !ok { output[c.FriendlyName] = []string{} } for _, d := range c.Values { output[c.FriendlyName] = append(output[c.FriendlyName], d.Value) } } } return output }