iris-contrib / middleware Goto Github PK
View Code? Open in Web Editor NEWCommunity Middleware List for the Iris Web Framework.
Home Page: https://github.com/kataras/iris
Community Middleware List for the Iris Web Framework.
Home Page: https://github.com/kataras/iris
I tried to implement the JWT middleware, but I encountered some problems. As when you generate the token you can set some params:
jwt.StandardClaims{
ExpiresAt: time.Now().Unix() + 60 * 60 * 24, // 1 day
Issuer: "test",
...
}
The middleware is doing checking for the ExpiresAt, but what about Issuer?
How does the middleware check for the Issuer and the other params (aud, jti, iat, iss, sub, etc.).
Is there a way to set these options in the middleware configs? Or I should somehow manually check for all these in another middleware?
I have two paths that diverge only by VERB (following REST principals).
The problem with the graceful package was fixed here https://github.com/kataras/iris/issues/198
But the cors middleware still has the same problem
There seems to be an bug in the JWT middleware which cause all token to be considered immediately expired. Here the logic is inversed:
Line 243 in 78279b7
According to the source code of underlying JWT library here:
https://github.com/dgrijalva/jwt-go/blob/06ea1031745cb8b3dab3f6a236daf2b0aa468b7e/claims.go#L69
and here:
https://github.com/dgrijalva/jwt-go/blob/06ea1031745cb8b3dab3f6a236daf2b0aa468b7e/claims.go#L104
The bool value returned by VerifyExpiresAt()
actually means not expired
, AKA currently valid
.
I was using iris-cors and rs/cors at the same time, and notice the APIs and docs are the same. Then I read the source code, and found out almost 100% identical, with slight modification.
https://github.com/iris-contrib/middleware/blob/v12/cors/cors.go
with
https://github.com/rs/cors/blob/master/cors.go
Correct me if I am wrong
customLogger := logger.New(iris.Logger, logger.Config{
EnableColors: true, //enable it to enable colors for all, disable colors by iris.Logger.ResetColors(), defaults to false
// Status displays status code
Status: true,
// IP displays request's remote address
IP: false,
// Method displays the http method
Method: true,
// Path displays the request path
Path: true,
})
iris.Use(customLogger)
Hi @kataras ,
I know this Question have been asked multiple times.But I am not able to understand how to implement the Iris.Any.
I have implemented my frontend in react and backend in iris.
When I am trying a PUT its throws CORS issue.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore not allowed access
I have configured CORS:
app := iris.New()
app.Use(cors.DefaultCors())
The API are as follows:
app.Post("/user/create",func(c *iris.Context){//db.insert...}
app.Put("/user/edit/:email",func(c *iris.Context){//db.update...}
.....
I have read on the previous answers that we need to user Iris.Any.
Can you please tell me how the Iris.Any will be implemented for the Api's above?Thanks in advance for your help.
Now I'd like to use i18n middleware in my project.
Is there any opportunity to translate the whole handler struct?
For example:
`
type indexHandler struct {
Title string
Lead string
}
func GetIndexHandler() *indexHandler {
return &indexHandler{
Title: "supersite", <-- here we set keys from somelang-ln-LN.ini
Lead: "under_construction", <-- here we set keys from somelang-ln-LN.ini
}
}
func (c *indexHandler) Serve(ctx *iris.Context) {
ctx.Render("index.html", structs.Map(c)) <-- instead of this I'd like some magic for example my18n.TranslateMap(c)
...
`
should I code helper func in middleware/i18n or is this opportunity already implemented in another way?
Thank you for checking out this issue!Merry Christmas Eve!Hope you have more harvest in the New Year!
And then there's my issue.
I find the jwt demo on this program,token := ctx.Values().Get("jwt").(*jwt.Token)
,it use the get reqeust.When I use the post request,I put the token into the Header,and get the Header :token := c.Ctx.Header("Authorization")
,yes I got the token,but how to change the type to the *jwt.Token and to decrypt the token?
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\secure.go:94:3: cannot use defaultBadHostHandler (type func("github.com/kataras/iris/v12/context".Context)) as type "github.com/kataras/iris/v12/context".Handler in field value
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\secure.go:133:20: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to s.badHostHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:88:24: cannot use unauthorizedHandler (type func("github.com/kataras/iris/v12/context".Context)) as type "github.com/kataras/iris/v12/context".Handler in assignment
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:143:11: cannot use cs.Serve (type func("github.com/kataras/iris/v12/context".Context)) as type "github.com/kataras/iris/v12/context".Handler in return argument
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:167:24: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:175:24: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:199:25: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:205:25: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:214:24: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
........\pkg\mod\github.com\iris-contrib\middleware\[email protected]\csrf.go:224:24: cannot use ctx (type "github.com/kataras/iris/v12/context".Context) as type *"github.com/kataras/iris/v12/context".Context in argument to cs.opts.ErrorHandler
after I update iris to the latest version, jwt handle code occor an error:
Cannot use 'middleware.JwtHandler().Serve' (type func(ctx iris.Context)) as the type context.Handler
// Serve the middleware's action func (m *Middleware) Serve(ctx iris.Context) { if err := m.CheckJWT(ctx); err != nil { m.Config.ErrorHandler(ctx, err) return } // If everything ok then call next. ctx.Next() }
param of Server ctx.iris.Context should changed to *context.Context
Describe the bug
Hello,
After playing with CSRF & HTTPS, it seems that Context.Request().URL is not correctly filled, hence failing the referrer check at that line:
valid := sameOrigin(ctx.Request().URL, referer)
To Reproduce
Steps to reproduce the behavior:
Expected behavior
We should get part of the URL depending on below schema:
scheme://host.domain:port/path/to/request
actually we're only getting the path part
/path/to/request
Screenshots
see attached screenshot if it helps
ctx.Request().URL showing the path
trying to query ctx.Request().URL.Host
Desktop (please complete the following information):
iris.Version
Additional context
Add any other context about the problem here.
Hi, I'm not sure if this is a bug or not but I hope you can shed some lights ๐.
For example, I have a WebAPI server such as http://localhost:1234/users
.
I then requested in this case using Vue-Resource to http://localhost:1234/users
.
Iris then automatically redirects me to http://localhost:1234/users/
.
It then returns me this error in Chrome's Console
XMLHttpRequest cannot load http://localhost:1234/users. Redirect from 'http://localhost:1234/users' to 'http://localhost:1234/users/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1234' is therefore not allowed access.
Here are my Iris implementation example
package main
import (
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
)
func main() {
iris.Use(cors.Default())
usersRoute := iris.Party("/users")
{
usersRoute.Get("/", handler)
usersRoute.Post("/", handler)
usersRoute.Delete("/:id", handler)
}
iris.Listen("localhost:1234")
}
func handler(ctx *iris.Context) {
ctx.JSON(iris.StatusOK, &iris.Map{"success": true})
}
Hi,
I found that in iris JWT middleware, if the JWT token is expired, a http statuscode 200 with empty response body will be returned. That's because the following code didn't call the errorHandler.
Lines 207 to 213 in e89d32e
Hello,
I found the problem with AllowedMethods
option.
Actually, this option works (unlike that the comments in source codes).
The problem comes from the non-existence of a routing for OPTIONS
HTTP method.
First i used:
app := iris.New()
app.UseGlobal(New(app, Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"PUT"},
}))
app.Put("/put", func(ctx iris.Context) { /* SOMETHING */ })
โฆ
It didn't work, when i tried:
curl -XOPTIONS http://localhost:3000/req/put
it returned a 404/Not Found
status
Therefore, PUT
route wasn't called in cross domain, cause OPTIONS
method returns 404 status.
But after that, i did this:
app := iris.New()
app.UseGlobal(New(app, Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"PUT"},
}))
app.Put("/put", func(ctx iris.Context) { /* SOMETHING */ })
// I added route for `OPTIONS` http method
app.Options("/put", func(ctx iris.Context) {})
โฆ
And it works.
To fix up that, it seems that app.UseGlobal
middlewares should be called even there is no route found and if the middleware calls ctx.Next()
, so it really send a 404 HTTP status to web client.
That's destined to app.UseGlobal
not for app.Use
, or the API shoud be extended to a new method app.UseDefault
or app.UseFinally
(like finally
in a try/catch/finally
block) which will be called in such situation.
Then, the cors middleware should check the route existence when OPTIONS
HTTP method is called, like that:
middleware_to_use_by_website_developpers := func(ctx context.Context) {
defer ctx.Next()
if ctx.Method() != "OPTIONS" {
return
}
uri := ctx.Request().RequestURI
method := ctx.GetHeader("Access-Control-Request-Method")
if RouteExists(uri, method) {
cors_middleware(ctx) // Call the original CORS middleware
}
}
Another thing, for a fully use of github.com/rs/cors
package, i recommends a new function in CORS middleware for Iris with signature func NewAllowAll() context.Handler
that use cors.AllowAll()
function of github.com/rs/cors
package, implemented like that:
func NewAllowAll() context.Handler {
return handlerconv.FromStdWithNext(cors.AllowAll().ServeHTTP)
}
AllowedMethods don't work.
Error message from React:
Failed to load http://localhost:5000/api/v1/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
app := iris.New()
app.WrapRouter(cors.WrapNext(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
}))
package main
import (
"github.com/iris-contrib/middleware/logger"
"github.com/kataras/iris"
)
var (
e = iris.New()
)
func hi(c *iris.Context) {
c.JSON(iris.StatusOK, iris.Map{
"Name": "Iris",
"Born": "13 March 2016",
"Stars": 4420,
})
}
// router
func router() {
e.Get("/hi", hi)
}
// setting
func setting() {
// e.Use(logger.New(e.Logger))
e.UseGlobal(logger.New(e.Logger))
e.Config.Gzip = true
}
// main
func main() {
router()
setting()
e.Listen(":8080")
}
Not resolved jwtHandler.Serve when use Jwt Middelware:
app := iris.New() jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{ ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { return []byte("My Secret"), nil }, SigningMethod: jwt.SigningMethodHS256, }) app.Use(jwtHandler.Serve)
i got this as an error when using the example
cannot use crs (type "github.com/kataras/iris/v12/context".Handler) as type "github.com/kataras/iris/context".Handler in argument to app.APIBuilder.Get
That's follows what i did on Fallback handlers, i noticed a malfunction.
The cause of problem is not in example, so i didn't posted issue in Iris Project or in Examples (iris-contrib/examples).
Fallback handlers in a Party is not called. Only Fallback handlers in Application scope are called.
Therefore, in CORS example which use CORS middleware, the Fallback handler defined in CORS middleware is not called.
The fallback handler is created in file iris-contris/middleware/cors/cors.go
at line 22 and is set in Party in the same file at line 71 (in function NewPartyMiddleware
called in CORS example).
The router, when no route is found, call the fallback handlers defined and registered in Application data structure (via Fallback stack), and even if the fallback stack is inherited in Party structure (APIBuilder
), this stay in Application scope.
The fallback handler is pushed in fallback stack that is in Party, but the router don't use it cause the fallback stack passed to the router (routerHandler
type ou RequestHandler
) is those which is in Application, not the Party, via RoutesProvider
interface instance (the app
object but indeed APIBuilder
in application).
I use iris v12.1.8 version in my program, is there a way to use jwt middleware?
I test the example code
package main
import "github.com/kataras/iris"
import "github.com/iris-contrib/middleware/cors"
func main() {
app := iris.New()
app.Use(cors.Default())
// app.Static("/static", "./static", 1)
app.Post("/user/create", func(ctx *iris.Context) {
ctx.Write("POST CREATE")
})
app.Listen(":3333")
}
It will pass when I send a post request, but fail if uncomment app.Static("/static", "./static", 1)
. The OPTIONS request will get the status code of "404 Not Found". And get the same result with OptionsPassthrough: true
.
go version go1.14.4 linux/amd64
programe:
package main
import (
"fmt"
"github.com/iris-contrib/middleware/cors"
"log"
"net"
"os"
)
func main() {
fmt.Println("Hello World!")
fmt.Println(os.Getuid())
f, err := os.Open("test.json")
if err != nil {
fmt.Printf("%s\n", err)
}
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
})
}
error :
$ go build hello.go
gowork/src/github.com/iris-contrib/middleware/cors/cors.go:144:10: cannot use c.Serve (type func("github.com/kataras/iris/context".Context)) as type "github.com/kataras/iris/context".Handler in return argument
otherwise:
in go.mod:
there is a conflict between
github.com/iris-contrib/middleware v12.1.2+incompatible and import github.com/iris-contrib/middleware/cors
app.Get("/metrics", iris.FromStd(promhttp.Handler()))
when request /metrics
in Chrome I got a file downloaded,
in Insomnia (a tool like postman) I got the right html content.
I am getting print for every below line in csrf
token request -
while trying to read formam: not found the field "csrf" in the path "csrf.Token" from the request body. Trace %!s(MISSING)
As the example code ,
jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("My Secret"), nil
},
SigningMethod: jwt.SigningMethodHS256,
Expiration: true,
})
I want to set expiration time ,
"ExpiresAt: time.Now().Add(time.Hour * time.Duration(1)).Unix()",
but how can i
Hello, I am trying to implement the New Relic service in one of my apps, but when I try to run the latest example that is here, the code ctx.HTML(`<h3 style="color:green;">%s</h3>`, "success")
doesn't output anything on the screen.
Any thoughts?
I am using the latest Iris version and Golang.
I am trying to include the JWT middleware with RS256 format and I keep getting key is of invalid type
The key and the JWT is the sample from the JWT test site
I've tried with both the public and the private keys, but I am still getting the same message
Is that the correct function signature?
HS256 works fine
// In Request, Aurorization Header:
Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.EkN-DOsnsuRjRO6BxXemmJDm3HbxrbRzXglbN2S4sOkopdU4IsDxTI8jO19W_A4K8ZPJijNLis4EZsHeY559a4DFOd50_OqgHGuERTqYZyuhtF39yxJPAjUESwxk2J5k_4zM3O-vtd1Ghyo4IbqKKSy6J9mTniYJPenn5-HIirE
// Code
var key = []byte("-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdlatRjRjogo3WojgGHFHYLugdUWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQsHUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5Do2kQ+X5xK9cipRgEKwIDAQAB-----END PUBLIC KEY-----")
var key = []byte("-----BEGIN RSA PRIVATE KEY-----MIICWwIBAAKBgQDdlatRjRjogo3WojgGHFHYLugdUWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQsHUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5Do2kQ+X5xK9cipRgEKwIDAQABAoGAD+onAtVye4ic7VR7V50DF9bOnwRwNXrARcDhq9LWNRrRGElESYYTQ6EbatXS3MCyjjX2eMhu/aF5YhXBwkppwxg+EOmXeh+MzL7Zh284OuPbkglAaGhV9bb6/5CpuGb1esyPbYW+Ty2PC0GSZfIXkXs76jXAu9TOBvD0ybc2YlkCQQDywg2R/7t3Q2OE2+yo382CLJdrlSLVROWKwb4tb2PjhY4XAwV8d1vy0RenxTB+K5Mu57uVSTHtrMK0GAtFr833AkEA6avx20OHo61Yela/4k5kQDtjEf1N0LfI+BcWZtxsS3jDM3i1Hp0KSu5rsCPb8acJo5RO26gGVrfAsDcIXKC+bQJAZZ2XIpsitLyPpuiMOvBbzPavd4gY6Z8KWrfYzJoI/Q9FuBo6rKwl4BFoToD7WIUS+hpkagwWiz+6zLoX1dbOZwJACmH5fSSjAkLRi54PKJ8TFUeOP15h9sQzydI8zJU+upvDEKZsZc/UhT/SySDOxQ4G/523Y0sz/OZtSWcol/UMgQJALesy++GdvoIDLfJX5GBQpuFgFenRiRDabxrE9MNUZ2aPFaFp+DyAe+b4nDwuJaW2LURbr8AEZga7oQj0uYxcYw==-----END RSA PRIVATE KEY-----")
func main() {
myJwtMiddleware := jwtmiddleware.New(jwtmiddleware.Config{
Debug: true,
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return key, nil
},
SigningMethod: jwt.SigningMethodRS256,
})
}
http info :
Request URL: http://localhost:8082/configure/login
Request Method: POST
Status Code: 403 Forbidden
Remote Address: [::1]:8082
Referrer Policy: no-referrer-when-downgrade
Content-Length: 18
Content-Type: text/plain; charset=utf-8
Date: Sun, 05 Jan 2020 17:04:38 GMT
Set-Cookie: _iris_csrf=MTU3ODI0Mzg3OHxJa1V6WW5GdVVGWkxZMDh5UlVKa2FVRkdlVGgxUlc5RFVYcDZhaXN6VGsxS1FWVXJjV042TlRoa2RXTTlJZ289fDk2KowXk6xVbzJOHubJBFJrEGX7KGKgzQsQw33BYR0H; HttpOnly; Secure
Accept: application/json, text/plain, /
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,la;q=0.6
Connection: keep-alive
Content-Length: 137
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Cookie: ph_qa=935ff80c-326d-4252-9e3d-0d4a5af84bb9
Host: localhost:8082
Origin: http://localhost:8082
Referer: http://localhost:8082/configure/login
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
X-CSRF-Token: M+z3NIX/gIYJJ9uXkisyzguxTGqVZxyQ74WiPNZtnm2vVD9DxSvfDNIWqh1whYakGd7bbRUy9KuYlTWJ6Bb3KA==
X-Requested-With: XMLHttpRequest
username: root
password: 123456
csrf.Token: M+z3NIX/gIYJJ9uXkisyzguxTGqVZxyQ74WiPNZtnm2vVD9DxSvfDNIWqh1whYakGd7bbRUy9KuYlTWJ6Bb3KA==
result:
CSRF token invalid
What should I do๏ผ
I found the code in cors.go changed here
pass := c.handlePreflight(ctx) || c.optionPassthrough if pass { ctx.Next() } else { ctx.SetStatusCode(iris.StatusOK) }
if handlePreflight return true it will always exec ctx.Next(),but in fact processing a pre-flight CORS request it should go to ctx.SetStatusCode(iris.StatusOK)
hi,I think there are some bugs in iris [or cors middleware],if the first method of routing is GET, then all OPTIONS request to method POST will response 404, if the first method of routing is POST, then all OPTIONS request to method GET will response 404, my iris version is 6.1.4, thank you
here is my code:
package main
import (
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
)
func main() {
crs := cors.New()
crs.AllowCredentials()
crs.AddOrigin("*")
r := iris.New(iris.Configuration{FireMethodNotAllowed: false, Gzip: false, IsDevelopment: true})
v1 := r.Party("/api/v1")
v1.Use(crs)
{
v1.Post("/home", func(c *iris.Context) {
fmt.Println("lalala")
c.WriteString("Hello from /home")
})
v1.Get("/g", func(c *iris.Context) {
fmt.Println("lalala")
c.WriteString("Hello from /home")
})
v1.Post("/h", func(c *iris.Context) {
fmt.Println("lalala")
c.WriteString("Hello from /home")
})
}
r.StaticWeb("/docs", "./html/apidoc/")
r.Listen(":8084")
}
curl -X OPTIONS 'http://127.0.0.1:8084/api/v1/home' -v
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8084 (#0)
> OPTIONS /api/v1/home HTTP/1.1
> Host: 127.0.0.1:8084
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Access-Control-Allow-Methods: OPTIONS
< Access-Control-Allow-Origin:
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< Date: Fri, 17 Feb 2017 05:30:25 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Curl_http_done: called premature == 0
* Connection #0 to host 127.0.0.1 left intact
curl -X OPTIONS 'http://127.0.0.1:8084/api/v1/g' -v
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8084 (#0)
> OPTIONS /api/v1/g HTTP/1.1
> Host: 127.0.0.1:8084
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Date: Fri, 17 Feb 2017 05:30:30 GMT
< Content-Length: 9
< Content-Type: text/plain; charset=utf-8
<
* Curl_http_done: called premature == 0
* Connection #0 to host 127.0.0.1 left intact
Not Found%
I have try the middleware,but it does not work
I find an easy way to handle this,maybe you can change
I copy from https://studygolang.com/articles/25389
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
})
app:= iris.New()
app.Use(crs())
unlike
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
})
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)`
Cors is not working even the official example in cors
directory.
when i want to make http request from jquery/ajax
it says :
XMLHttpRequest cannot load http://localhost:8088/api/v1/home. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.
Hi, I need extract jwt token from cookies, can add Extractor like this?
....
// FromCookies returns a function that extracts the token from the specified
// query string cookies
func FromCookies(name string) TokenExtractor {
return func(ctx context.Context) (string, error) {
value := ctx.GetCookie(name)
return value, nil
}
}
....
Thanks
go get github.com/iris-contrib/middleware/jwt@master
go: finding module for package github.com/klauspost/compress/snappy
go: finding module for package github.com/klauspost/compress/snappy
../../pkg/mod/github.com/kataras/iris/[email protected]/context/compress.go:14:2: module github.com/klauspost/compress@latest found (v1.12.3), but does not contain package github.com/klauspost/compress/snappy
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"OPTIONS", "GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"*"},
})
api := iris.New(c)
api.Use(crs)
tick := api.Party("/om/tickets", authzSupport, loadTicketClient)
{
tick.Get("/", tickets.OldestUnresponded)
tick.Get("/:id", authzSupport, loadTicketClient, tickets.GetTicketByID)
tick.Post("/:id/respond", authzSupport, loadTicketClient, tickets.Respond)
}
The OPTIONS call to /:id/respond is 404'ing. I have even tried manually adding a tick.Options() call and iris is still returning a 404 for the options call.
CORS is operating for the root and detail calls, but not the subroute to details.
Any help is appreciated.
Now Recovery just prints Recovery from panic
;
func (r recovery) Serve(ctx *iris.Context) {
defer func() {
if err := recover(); err != nil {
r.out.Write([]byte("[IRIS:" + time.Now().String() + "] Recovery from panic \n"))
//ctx.Panic just sends http status 500 by default, but you can change it by: iris.OnPanic(func( c *iris.Context){})
ctx.Panic()
}
}()
ctx.Next()
}
Why not print panic err message by default here?
https://github.com/iris-contrib/middleware/blob/master/casbin/casbin.go#L72
this line of code get username
only by BasicAuth
In production environment, there will be other types of auth, such as session, token, jwt, OAuth...
New to Iris and really like it!
Following your new article:
https://medium.com/@kataras/how-to-use-iris-and-postgresql-for-web-development-e8c46d72f1e6
I was able to use the pg middleware for testing. It seem I cannot do update!
The error I got: transaction: exec: mismatched param and argument count
type User struct {
Id string `json:"id" pg:"type=uuid,primary"`
CreatedAt time.Time `json:"createdAt" pg:"type=timestamp,default=clock_timestamp()"`
UpdatedAt time.Time `json:"updatedAt" pg:"type=timestamp,default=clock_timestamp()"`
Email string `json:"email" pg:"type=varchar(255),username,unique"`
Password string `json:"password" pg:"type=varchar(32),password"`
FirstName string `json:"firstName" pg:"type=varchar(255)"`
MiddleName *string `json:"middleName" pg:"type=varchar(255),null"`
LastName string `json:"lastName" pg:"type=varchar(255)"`
Sex *string `json:"sex" pg:"type=char(1),null"`
}
func (c UserController) Update(ctx iris.Context) {
var u User
var errPg error
err := ctx.ReadJSON(&u)
if err != nil {
ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
Title("User Update failure").DetailErr(err))
return
}
userRepo := pg.Repository[User](ctx)
_, errPg = userRepo.Update(ctx, u)
if errPg != nil {
if pg.IsErrNoRows(errPg) {
ctx.StopWithStatus(iris.StatusNotFound)
} else {
ctx.StopWithError(iris.StatusInternalServerError, errPg)
}
return
}
ctx.StatusCode(iris.StatusOK)
}
From Postman I Put:
{
"id": "6c051e51-9c64-49f7-a6ce-977cd7b2030a",
"email": "[email protected]",
"password": "Ironman",
"firstName": "Tony",
"middleName": "",
"lastName": "Stark",
"sex": "M"
},
Same error if I add my CreatedAt and UpdatedAt in my json
I tried to debug further, and it remove my audit dates because there are timestamp and put my id at the end not sure what it try to do.
Any help will be appreciated!
My project is here:
https://github.com/aleblanc70/events/blob/main/web/main.go
Thanks!
I have the following code...
iris.Use(cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{
"GET", "OPTIONS", "POST",
"PATCH", "PUT", "DELETE",
},
}))
However I get a CORS error in my js console?
create:1 Fetch API cannot load http://releases.bandzest.dev/api/v1/releases. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
However I can access the API from postman, strange.
Code in your CORS module.
In your example
of cors, there is a line:
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)
however, the AllowMethods
is not exists.
Also, in your cors_test.go
, app.AllowMethods
is also invalid.
Hi, i'm getting the following error when making a request to Iris with angularjs resource:
XMLHttpRequest cannot load http://externalurl.com:3001/action. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I have CORS configured this way on main.go file:
//Cors
iris.Use(cors.New(cors.Options{
AllowedMethods: []string{"GET", "POST", "OPTIONS", "HEAD"},
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"*"},
OptionsPassthrough: true,
MaxAge: 3600,
}))
Any idea what i'm missing here?, thanks for your help.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.