Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication middleware example #8

Closed
Tagnard opened this issue Feb 19, 2019 · 2 comments
Closed

Authentication middleware example #8

Tagnard opened this issue Feb 19, 2019 · 2 comments

Comments

@Tagnard
Copy link

Tagnard commented Feb 19, 2019

Do you have an example on how to implement a authentication middleware that only authenticates part of the endpoints and not all of them?

Thanks in advance.
//Tagnard

@sarulabs
Copy link
Owner

I'm not sure I understand your question and I don't think it is related to this project.

Let's consider that a middleware is a function which takes an http.HandlerFunc (and maybe some other parameters) and returns an other http.HandlerFunc. The HTTPMiddleware function from this project fits this description.

You can see it used here : https://github.com/sarulabs/di-example/blob/9cccc2792366dfce074c66a82e1563758c07c9f0/main.go#L42

m is a middleware that combines two middlewares. One to recover from a possible panic, and the other one to inject the dependency injection container in the request. If you have an authentication middleware, you can add it here.

For example you can create ma to add the authentication middleware to m:

ma := func(h http.HandlerFunc) http.HandlerFunc {
    return m(AuthenticationMiddleware(h))
}

and then you can decide to apply m or ma depending on the route:

r.HandleFunc("/cars", m(handlers.GetCarListHandler)).Methods("GET") // without authentication
r.HandleFunc("/cars", ma(handlers.PostCarHandler)).Methods("POST") // with authentication

Hope it helps.

@Tagnard
Copy link
Author

Tagnard commented Feb 19, 2019

Thanks for the example, this will help me greatly!

@Tagnard Tagnard closed this as completed Feb 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants