Comments (9)
I would recommend to use interceptors:
// client
grpc.Dial(target,
grpc.WithInsecure(),
grpc.WithPerRPCCredentials(&loginCreds{
Username: "admin",
Password: "admin123",
}))
type loginCreds struct {
Username, Password string
}
func (c *loginCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{
"username": c.Username,
"password": c.Password,
}, nil
}
func (c *loginCreds) RequireTransportSecurity() bool {
return true
}
// server
grpc.NewServer(
grpc.StreamInterceptor(streamInterceptor),
grpc.UnaryInterceptor(unaryInterceptor)
)
func streamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := authorize(stream.Context()); err != nil {
return err
}
return handler(srv, stream)
}
func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if err := authorize(ctx); err != nil {
return err
}
return handler(ctx, req)
}
func authorize(ctx context.Context) error {
if md, ok := metadata.FromContext(ctx); ok {
if len(md["username"]) > 0 && md["username"][0] == "admin" &&
len(md["password"]) > 0 && md["password"][0] == "admin123" {
return nil
}
return AccessDeniedErr
}
return EmptyMetadataErr
}
from grpc-go.
I can't figure out how to use simple password based authentication. If I use TransportAuthenticator, https://github.com/grpc/grpc-go/blob/master/transport/http2_client.go#L127 won't let me have TLS and password based auth at the same time. I can't figure out how to use per request based authentication either.
A small tutorial or a snippet of code would be highly appreciated.
EDIT: I figured out how to use per request RPC auth. It's all about sharing metadata. For my fellow grpc-go users (and noobs, like me), I'm leaving it here. On your server, have something like:
md, _ := metadata.FromContext(ctx)
if !authenticate(md["username"], md["password"]) {
return nil, ErrAuthenticationFailed
}
On the client side, you need to have:
type passCredential int
func (passCredential) GetRequestMetadata(ctx context.Context) (map[string]string, error) {
return map[string]string{
"username": "admin",
"password": "admin123", // Stupid password.
}, nil
}
Then, while dialling to the server:
var cred passCredential
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithPerRPCCredentials(cred))
Still couldn't figure out how to do auth once and store it in the context.
from grpc-go.
@ishbir Make a call to AuthenticationService{}.Authenticate(user, pass) on the server. Make this function on the server to create a session token, store it in memory (memcache or redis) and return it to the client. Then have the client set this session token in metadata; and have the server verify it against the session store.
Or use JWT (with exp) instead of session tokens to avoid the DB trip.
from grpc-go.
On Fri, Mar 6, 2015 at 11:55 PM, prazzt [email protected] wrote:
I'm trying to figure out how to authenticate requests in simple password
based/session token case.Should I :
- create my own proto, embedding token in each message ? or
- do it in grpc: implementing my own credential.Credentials ? how to
check server side ?I would suggest using the metadata to transmit the passwd/token. Please
take a look at
https://github.com/grpc/grpc-go/blob/master/test/end2end_test.go#L353 for
how a client sets metadata for an RPC and
https://github.com/grpc/grpc-go/blob/master/test/end2end_test.go#L92 for
how a server gets the metadata.
Would appreciate if there's some basic examples.
—
Reply to this email directly or view it on GitHub
#106.
from grpc-go.
How would this work to do connection based authentication? So that you don't have to check password for each rpc call?
from grpc-go.
I've seen https://godoc.org/google.golang.org/grpc/credentials#TransportAuthenticator, but it would be nice to have an example of how this would work in practice.
from grpc-go.
credentials.tlsCreds is one example. You can look at
i) the simple HOWTO https://github.com/grpc/grpc-go/blob/master/grpc-auth-support.md;
ii) examples/route_guide for an example (both client and server).
from grpc-go.
@amenzhinsky your code keeps yelling me with
grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)
something has changed?
from grpc-go.
@milewski, seems like now you have to pass grpc.WithInsecure()
to grpc.Dial
explicitly unless you set transport credentials.
from grpc-go.
Related Issues (20)
- grpc.NewClient with namedpipe on Windows throws resolverError HOT 2
- User agent becomes grpc-go/1.64. on server side of grpc gateway HOT 3
- xds: move functionality from `xds/internal` to `internal/xds`
- stubserver: add support to optionally pass in a `grpc.Server` or `xds.GRPCServer` HOT 2
- Github Action: Codecov action is broken and is failing silently HOT 1
- Upgrade to using math/rand/v2 to get perf enhancements HOT 2
- xds: tests shouldn't rely on the presence of an entry in the `authorities` field of the bootstrap configuration with an empty key
- Experimental API related to metadata HOT 4
- Linter rule for using context.Background() without a timeout in tests HOT 4
- gRPC is incompatible with tls.Listener HOT 2
- Closing connection takes up to 15 minutes. HOT 5
- Feature Request: expose handleRawConn or add ServeConn HOT 26
- Flaky test: TimerAndWatchStateOnErrorCallback HOT 4
- xds: bootstrap config is not emitted to logs in a human readable way
- Strongly-type request inside a Stream Server Interceptor HOT 2
- Proxy connection buffer necessary? HOT 1
- Why does grpc.NewClient silently ignore DialOptions? HOT 2
- Make transport.SetConnection public? HOT 4
- what's the default max data size
- If a priority contains multiple localities with pick_first, load is reported incorrectly HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from grpc-go.