No Password Authentication: server

Source: Internet
Author: User
Tags email string all mail cockroachdb

No password verification allows you to enter only one email without entering a password to log in to the system. This is a more secure way to log in than traditional email/password authentication methods.

Below I will show you how to implement an HTTP API in go to provide this service.

Process

    • The user enters his e-mail address.
    • The server creates a temporary one-time-use code (like a temporary password) associated to the user and then sends a "magic link" to the user's mailbox.
    • The user clicks on the Magic link.
    • The server extracts the code from the Magic link, gets the associated user, and redirects to the client with a new JWT.
    • Each time a new request is available, the client uses JWT to authenticate the user.

Required conditions

    • Database: We used a SQL database called COCKROACHDB for this service. It's very much like Postgres, but it's written with Go.
    • SMTP Server: We will use a third-party mail server to send mail. When developing, we use Mailtrap. Mailtrap sends all mail to its inbox, so you don't need to create multiple fake mail accounts when testing.

Install it from the Go home page, and then use the go version (1.10.1 atm) command to check if it works.

Download it from the COCKROACHDB home page, expand it, and add it to your PATH variable. Use the cockroach version (2.0 atm) command to check whether it works correctly.

Database schema

Now, we GOPATH create a directory for this project under the directory, and then use the cockroach start start a new COCKROACHDB node:

cockroach start --insecure --host 127.0.0.1

It will output some content, find the SQL address line, and it will display postgresql://root@127.0.0.1:26257?sslmode=disable content like this. We'll use it later to connect to the database.

Use the following content to create a schema.sql file.

DROP DATABASE IF EXISTS passwordless_demo CASCADE;CREATE DATABASE IF NOT EXISTS passwordless_demo;SET DATABASE = passwordless_demo;CREATE TABLE IF NOT EXISTS users (    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),    email STRING UNIQUE,    username STRING UNIQUE);CREATE TABLE IF NOT EXISTS verification_codes (    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),    user_id UUID NOT NULL REFERENCES users ON DELETE CASCADE,    created_at TIMESTAMPTZ NOT NULL DEFAULT now());INSERT INTO users (email, username) VALUES    ('john@passwordless.local', 'john_doe');

This script creates a database named, passwordless_demo two users tables named and verification_codes , and some dummy users inserted for later testing. Each validation code is associated with the user and saves the creation time, which is used to check that the validation code is out of date.

Use the command in another terminal cockroach sql to run the script:

cat schema.sql | cockroach sql --insecure

Environment configuration

You need to configure two environment variables: SMTP_USERNAME and SMTP_PASSWORD , you can get them from your Mailtrap account. They will be used in our program.

Go dependent

We need the following Go packages:

    • GITHUB.COM/LIB/PQ: It is the Postgres drive used by COCKROACHDB
    • Github.com/matryer/way: Router
    • GITHUB.COM/DGRIJALVA/JWT-GO:JWT implementation
go get -u github.com/lib/pqgo get -u github.com/matryer/waygo get -u github.com/dgrijalva/jwt-go

Code

initialization function

Create main.go and init start by getting some configuration from the environment variables in the function.

var config struct {port int appurl *url. URL databaseurl string Jwtkey []byte smtpaddr string Smtpauth smtp. Auth}func init () {config.port, _ = StrConv. Atoi (env ("PORT", "a")) Config.appurl, _ = URL. Parse (env ("App_url", "http://localhost:" +strconv. Itoa (Config.port) + "/") Config.databaseurl = env ("Database_url", "Postgresql://root@127.0.0.1:26257/passwordless_  Demo?sslmode=disable ") Config.jwtkey = []byte (env (" Jwt_key "," Super-duper-secret-key ")) SMTPHost: = env (" SMTP_HOST ", "Smtp.mailtrap.io") config.smtpaddr = net. Joinhostport (SMTPHost, env ("Smtp_port", "+")) Smtpusername, OK: = OS. Lookupenv ("Smtp_username") if!ok {log. Fatalln ("Could not find smtp_username on environment variables")} Smtppassword, OK: = OS. Lookupenv ("Smtp_password") if!ok {log. Fatalln ("Could not find Smtp_password on environment variables")} Config.smtpauth = SMTP. Plainauth ("", Smtpusername, Smtppassword, SMTPHost)}func Env (key, Fallbackvalue string) string {V, OK: = OS. Lookupenv (key) if!ok {return fallbackvalue} return v}
    • appURLwill be going to build our "Magic link".
    • portThe HTTP server that will be started.
    • databaseURLis the COCKROACHDB address, I add /passwordless_demo the previous database address to represent the database name.
    • jwtKeyUsed to sign a JWT.
    • smtpAddris SMTP_HOST the SMTP_PORT Union of +, we will use it to send mail.
    • smtpUsernameAnd smtpPassword is a two required variable.
    • smtpAuthAlso used to send messages.

envThe function allows us to get an environment variable that returns a fallback value when it does not exist.

Main function

  var db *sql. Dbfunc Main () {var err error if db, err = sql. Open ("Postgres", Config.databaseurl); Err! = Nil {log. Fatalf ("Could not open database connection:%v\n", err)} defer db. Close () If Err = db. Ping (); Err! = Nil {log. Fatalf ("Could not pings to database:%v\n", err)} Router: =. Newrouter () router. Handlefunc ("POST", "/api/users", jsonrequired (createUser)) router. Handlefunc ("POST", "/api/passwordless/start", jsonrequired (Passwordlessstart)) router. Handlefunc ("GET", "/api/passwordless/verify_redirect", Passwordlessverifyredirect) router. Handle ("GET", "/api/auth_user", authrequired (Getauthuser)) Addr: = Fmt. Sprintf (":%d", config.port) log. PRINTF ("Starting server at%s  

compiled from: https://nicolasparada.netlify.com/posts/ passwordless-auth-server/ author: Nicolás Parada
Original: LCTT https://linux.cn/article-9748-1.html translator: QHWDW

This article by LCTT original translation, Linux China starter. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Lctt!
Translation work and translations published for learning and communication purposes only, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work violates your rights, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translated link and the author/translator in the text.
article represents the author's knowledge and views, if there are different points of view, please queue up downstairs:D

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.