Security defines authentication requirements to access an entire API, service or individual service method. The requirement refers to one or more OAuth2Security, BasicAuthSecurity, APIKeySecurity, BearerSecurity or JWTSecurity security scheme. If the schemes include a BearerSecurity, OAuth2Security
(args ...any)
| 322 | // }) |
| 323 | // }) |
| 324 | func Security(args ...any) { |
| 325 | var dsl func() |
| 326 | if d, ok := args[len(args)-1].(func()); ok { |
| 327 | args = args[:len(args)-1] |
| 328 | dsl = d |
| 329 | } |
| 330 | |
| 331 | schemes := make([]*expr.SchemeExpr, len(args)) |
| 332 | for i, arg := range args { |
| 333 | switch val := arg.(type) { |
| 334 | case string: |
| 335 | for _, s := range expr.Root.Schemes { |
| 336 | if s.SchemeName == val { |
| 337 | schemes[i] = expr.DupScheme(s) |
| 338 | break |
| 339 | } |
| 340 | } |
| 341 | if schemes[i] == nil { |
| 342 | eval.ReportError("security scheme %q not found", val) |
| 343 | return |
| 344 | } |
| 345 | case *expr.SchemeExpr: |
| 346 | if val == nil { |
| 347 | eval.InvalidArgError("security scheme", val) |
| 348 | return |
| 349 | } |
| 350 | schemes[i] = expr.DupScheme(val) |
| 351 | default: |
| 352 | eval.InvalidArgError("security scheme or security scheme name", val) |
| 353 | return |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | security := &expr.SecurityExpr{Schemes: schemes} |
| 358 | if dsl != nil { |
| 359 | if !eval.Execute(dsl, security) { |
| 360 | return |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | current := eval.Current() |
| 365 | switch actual := current.(type) { |
| 366 | case *expr.MethodExpr: |
| 367 | actual.Requirements = append(actual.Requirements, security) |
| 368 | case *expr.ServiceExpr: |
| 369 | actual.Requirements = append(actual.Requirements, security) |
| 370 | case *expr.APIExpr: |
| 371 | actual.Requirements = append(actual.Requirements, security) |
| 372 | case expr.SecurityHolder: |
| 373 | actual.AddSecurityRequirement(security) |
| 374 | default: |
| 375 | eval.IncompatibleDSL() |
| 376 | return |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // NoSecurity removes the need for an endpoint to perform authorization. |
| 381 | // |