简体   繁体   中英

API Authentication flow

I'm currently writing an API in Go and have been racking my brain over how to do authentication/authorization correctly and securely.

As I understand it, this is how it goes:

  • New user registers for account via api/user/register endpoint (or api/user/login for existing users)
  • Server receives request and checks that username is unique, etc. After that, it issues (if all is well) an access token and refresh token , both signed for added security.
  • The client app receives the tokens and stores them in the browser cookie (or local/session Storage) and makes sure to send them securely over HTTPS in any subsequent requests to the API.
  • When receiving requests to protected routes, the server checks the access token's expiry date, and if expired, will check the refresh token's validity in the database. If it's invalid, ask for reauthentication clientside. Otherwise, reissue a new access token.

My questions are regarding the steps dealing with refresh tokens .

I am also writing the client application (in React); I won't be releasing the API to the public. I simply am writing the backend as an API for the client app.

  • Should I still use refresh tokens?
  • Do I need an api/auth/token route? I keep reading about them in implementation examples and I feel like I can just have some helper functions to query the database and reissue tokens in my backend code instead of having to query another endpoint to do so.

Sorry if they're dumb questions, but I've been poring over page after page detailing the auth spec, and the subtle differences from page to page are leaving me confused and unsure of what is truly "best practice" in production.

I think you are confusing this over the word login. Instead of /api/user/login I call it /api/user/authentication . So if the request has a json attached to its body, it return a valid token. But if the request got a Authentication Header that is valid, you just issue a new token valid for the same period of time. This is specially good for frontends, so you could try to re-auth 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM