Coder Social home page Coder Social logo

Comments (9)

amenzhinsky avatar amenzhinsky commented on July 19, 2024 63

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.

ishbir avatar ishbir commented on July 19, 2024 24

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.

Gurpartap avatar Gurpartap commented on July 19, 2024 2

@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.

iamqizhao avatar iamqizhao commented on July 19, 2024

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.

GeertJohan avatar GeertJohan commented on July 19, 2024

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.

GeertJohan avatar GeertJohan commented on July 19, 2024

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.

iamqizhao avatar iamqizhao commented on July 19, 2024

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.

milewski avatar milewski commented on July 19, 2024

@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.

amenzhinsky avatar amenzhinsky commented on July 19, 2024

@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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.