API Authentication Flow

I am currently writing an API in Go and I am trying how to do the authentication / authorization correctly and securely.

As I understand it, this is how it is:

  • New user signs up for account via endpoint api/user/register

    (or api/user/login

    for existing users)
  • The server receives the request and checks that the username is unique, etc. After that, it issues (if all is well) an access token and a refresh token , both signed for added security.
  • The client application receives the tokens and stores them in the browser cookie (or local / session storage) and be sure to send them securely over HTTPS in any subsequent API requests.
  • When receiving requests to protected routes, the server checks the expiration date of the access to the token and, if it has expired, checks the relevance of the refresh token in the database. If it is not valid, ask to re-authenticate clients. Otherwise, reissue a new access token.

My questions are about the steps related to refresh tokens .

I am also writing a client application (in React); I will not release the API to the public. I am just writing the backend as an API for a client application.

  • Should I use refresh tokens?
  • Do I need a route api/auth/token

    ? I keep reading about them in the implementation examples and I feel like I can just have some helper functions to query the database and reuse tokens in my backend code instead of asking for a different endpoint to do this.

Sorry if these are stupid questions, but I've been going through page after page detailing the auth spec, and the subtle differences from page to page leave me confused and unsure of what is really "best practice" in production.

+3


source to share


1 answer


I think you are misleading this over the word login. Instead, /api/user/login

I call it /api/user/authentication

. So if the request has a json attached to its body, it returns a valid token. But if the request received an authentication header that is valid, you simply issue a new token valid for the same period of time. This is especially useful for interfaces, so you can try to auto-update automatically.



newUser := types.User{}
if r.Body != nil {
     err := json.NewDecoder(r.Body).Decode(&newUser)
     ... 
}
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
    _, err := USERAUTH.CHeckJWT(w,r)
    if err !=nil {
    ...,
    }
    newToken := GenerateTokenFromToken(token)
}

      

0


source







All Articles