goa v2で一番単純なBasicAuthを実装するまで
- design.goにBasicAuthSecurityを追加します。
package design // The convention consists of naming the design // package "design" import ( . "github.com/goadesign/goa/design/apidsl" ) var _ = API("area", func() { // API defines the microservice endpoint and Title("area API") // other global properties. There should be one Description("A simple goa service") // and exactly one API definition appearing in Scheme("http") // the design. Host("localhost:8080") }) var BasicAuth = BasicAuthSecurity("BasicAuth", func() { //←これ追加 Description("Use client ID and client secret to authenticate") })
- Resource(同じくdesign.goの中)に↑で宣言したBasicAuthを追加します。
var _ = Resource("point", func() { // Resources group related API endpoints BasePath("/points") // together. They map to REST resources for REST DefaultMedia(PointMedia) // services. Security(BasicAuth) //←これ追加 ・・・・
goagen bootstrapした後のmain.goに追記します。
package main import ( "github.com/goadesign/goa" "github.com/goadesign/goa/middleware" "github.com/goadesign/goa/middleware/security/basicauth" "github.com/hryktrd/goaTest/app" ) func main() { // Create service service := goa.New("area") app.UseBasicAuthMiddleware(service, basicauth.New("admin", "password")) //←これ追加
これでgo buildしてpostmanなどで適当なAPIにアクセスすると
{"id":"SqvDzqfu","code":"basic_auth_failed","status":401,"detail":"Authentication failed"}
みたいに返ってきて認証失敗するようになりました。 上で
basicauth.New
したときの ID/PW = admin/passwordを設定してみるとAPIにアクセスできるようになりました。