×

Authentication / Authorization Method | Hachinet Software

One of the most important issues in building a web application is how to verify a user's ID. Then, you need to understand two concepts: user authentication and user authorization. Let Hachinet show you how to create trusted digital transactions by implementing proper user identification and authentication methods.

Authentication / Authorization Method | Hachinet Software

 2022-03-29

Authentication / Authorization Method | Hachinet Software

One of the most important issues in building a web application is how to verify a user's ID. Then, you need to understand two concepts: user authentication and user authorization. Let Hachinet show you how to create trusted digital transactions by implementing proper user identification and authentication methods.

 

Authentication/Authorization

  • User Authentication is the process of verifying the login information of a device or user to access the system.
  • Authorization is the process of verifying whether a user or device is authorized to perform a particular task on a particular system.

 

→ Here is a brief explanation.

  • Authentication is the question "Who are you?"
  • Authorization is a question of "What can I do?"

You can see that Authentication is always done before "Authorization". This means that you need to authenticate your identity before you can perform Authorization. So what are the "consignment" or user authentication methods for web applications?

 

 

1. HTTP / HTTPS


To understand how a user's identity authentication is identified, you first need to understand the protocol used by your website. Here, it is "HTTP" and "HTTPS". The difference between the two protocols is that HTTPS data is secure. However, it makes requests/responses separately between the client and the server.

 

When the client requests the server, the server creates an account in the database and returns an HTTP status of 200 OK. However, for the following statement, the server cannot know if the client sending this request is the previous client.

 

Ex: On a website (blog), on the other hand, users create an account and post. Therefore, the server cannot determine the previous account creation request, and is the request the same person?

 

To solve this problem, HTTP integrates authentication in the header of each request.

 

【"Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" your-website.com

 

The user's login information will be reconnected and encrypted. (Ex: dXNlcm5hbWU6cGFzc3dvcmQ), the encryption method here is "base64".

 

     base64.

        let auth = 'username:password';

            let encode = btoa(auth);

         let decode = atob(encode);

 authHttp

 

How HTTP / HTTPS works

  1. The client implements a request for access to restricted resources.
  2. The server sends to HTTP 401 Unauthorized by using the title [WWW-Authenticate by Base Value].
  3. After that, the client encrypts the client's [user name and password] and requests it from the server.
  4. When the server authenticates the user ID, a [Authorization: Basic dcdvcmQ =] section is added for each request.

 

 

★Advantages

  • Speed up and don't take a lot of time
  • Easy to deploy.
  • You can also run it in any browser.

★Disadvantages

  • The Base64 encoding method is easy to decode. The username and password are the information you need to log in, so if hacked and decrypted, the user may lose their account.
  • You need to authenticate your ID on each request.
  • Users can only log out by logging in with invalid information.

 

import basicAuth from 'basic-auth';

function unauthorized(res) {

    res.set('WWW-Authenticate', 'Basic realm=Authorization Required');

    return res.send(401);};

 

export default function auth(req, res, next) {

    const {name, pass} = basicAuth(req) || {};

    if (!name || !pass) {

        return unauthorized(res);

 

Note: In some cases, you can encode using MD5 instead of base64, which is secure but less efficient.

 

 

2. Session-Cookies


In addition, "session-cookies" based authentication stores the user state on the server and creates the user's sessionId after the first valid login, rather than requiring a username and password for each request. Then the matter is sent to the client

 

The client "browser" stores the sessionId in a Cookie. Therefore, you only need to send the session ID every time there is a request to the server.

 

Session information is stored in the following cookies:

 cookie

 

★How Session-Cookies work

  1. The client sends a valid authentication message back to the server.
  2. After authenticating the information, the server creates and stores the session ID. Then, by adding it to HTTP using "Set-Cookie" in the header, it will be reflected in the client.
  3. The client receives a "sessionId" stored in the browser. Each subsequent request is also sent to the server.

 

★Advantages

  • Since the only information contained in the HTTP request is sessionId, it is more secure than the HTTP method above.
  • Subsequent logins will be faster because login does not require any required information.
  • It's easy to do.

★Disadvantages

Cookies are a useful feature, but there are some situations to watch out for. That is when using a shared PC or tablet terminal used by an unspecified number of people. If you enter personal information on a shared PC or tablet device to access the website, the personal information stored by cookies may be confirmed by subsequent users.

 

In such situations, prevent information leakage by blocking/deleting cookies or not using websites that enter personal information. Also, from the user's point of view, displaying ads by retargeting as mentioned above can be annoying. You should avoid displaying web ads that are so persistent that users block cookies. It is also vulnerable to CSRF attacks.

 

const express = require('express');

   const sessions = require('express-session');

        const app = express();

           const oneDay = 1000 * 60 * 60 * 24;

        app.use(sessions({

 

    secret: "thisismysecrctekeyfhrgfgrfrty84fwir767",

       saveUninitialized:true,

    cookie: { max Age: oneDay },

    resave: false 

}));

 

 

3. Token


Strictly speaking, "token" is a synonym for "cryptocurrency" and "virtual currency". However, gradually, depending on the context, it has become more specific than the other two. Firstly, it refers to all crypto assets except Bitcoin and Ethereum.

 

Secondly, it refers to a particular crypto asset running on the blockchain of other crypto assets, as is the case with many decentralized financial (or DeFi) tokens. Tokens have a wide range of potential features, from enabling decentralized transactions to selling rare items in video games. At the same time, any token can be traded and held like any other crypto asset.

 

Token is a word often heard in crypto assets. In fact, you may hear the explanation that Bitcoin is a "cryptocurrency token" or the like. Because, strictly speaking, all crypto assets are tokens. However, as the word gradually becomes more common enough to have two concrete meanings, it is quite possible that you will come across this meaning. 

 

"Token" often refers to any crypto-asset other than Bitcoin and Ethereum (strictly speaking, these are also tokens). Another, increasingly common meaning of tokens has even more specific implications and refers to crypto-assets running on the blockchain of other crypto assets. If you become interested in decentralized finance (or DeFi), you will come across this usage.

 

Cryptocurrencies like Bitcoin have their own blockchains, while DeFi tokens like Chainlinks and Aave run on and utilize existing blockchains. The most common of these blockchains is Ethereum. 

 

 

★How Token works

Request: The user requests access to a server or protected resource. At this time, log in using a password or other specified process may be involved.

 

Validation: The server determines that the user may access it. At this time, user name and password collation and other specified processes may be involved.

 

Token: The server communicates with the authentication device (ring, key, mobile phone, etc.). After validation, the server issues a token and passes it to the user.

 

Storage: The token stays in the user's browser for the duration of the operation. When the user tries to access another part of the server, the token communicates with the server again. Access is granted or denied based on the token.

 token

 

The JWT chain contains three parts.

  • Header: Contains the algorithms used to encode the data type and JWT chain.
  • Payload: Contains information to enter in the token string, such as username, user ID, creator, etc.
  • Signature: Generates the header payload encrypted with a secret string (private key).

 

The administrator sets the token limit. For example, you can set a one-time token that will be destroyed immediately when the user logs out. You can also set the token to self-destruct at the end of the specified time period.

 

Ex: 

data = ''base64urlEncode''( header ) + "." + base64urlEncode( payload )

signature = Hash( data, secret_key );

 

★Advantages

  • The size of this code language token is small and can be quickly passed between two entities.
  • Ease of use: Tokens can be generated from almost anywhere and do not need to be validated on the server.
  • Control: You can specify what the user can access, how long the permission lasts, and what you can do while logged on.

★Disadvantages

  • Single key: JWT depends on a single key. If this key is compromised, the entire system is at risk.
  • Complexity: These tokens are not easy to understand. If the developer does not have sufficient knowledge of cryptographic signature algorithms, it can accidentally endanger the system.
  • Constraint: You cannot push a message to all clients. Also, you cannot manage clients from the server-side.

 

const jwt = require('jsonwebtoken');

 

const generateToken = (payload) => {

    return jwt.sign(payload, process.env.JWT_SECRET, {

        expiresIn: process.env.JWT_EXPIRE,

    });

};

module.exports = generateToken;

 

 

4. OAuth


Understanding OAuth and MRA - Cisco Community

 

OAuth is a mechanism used to operate multiple Web services in cooperation. Normally, in order to use Web services, it is necessary to individually enter a user ID and password to authenticate the user, but by using OAuth, interlocking between applications can be done without entering an ID and password.

 

★How OAuth works

OAuth holds user information and resources and is an application that authenticates (service provider), an application that receives authentication and operates user resources owned by the service provider (consumer), and a user who owns the resource. It is realized by exchanging data.

In the previous example, the "service provider" is Twitter, the "consumer" is the online album application, and the "user" is you.

 

★Advantages

  • OAuth 2.0 is a flexible protocol based on SSL for storing user tokens.
  • Allow access to user information and allow access when the authentication token expires.
  • You can share data with users without disclosing personal information.
  • Easy to implement and highly reliable.

 

★Disadvantages

  • Usage rights may be abused.
  • Since OAuth passes the entire authentication information to the linked application, etc., if a malicious program is installed in the linked application, etc., the usage authority may be abused and damage such as spoofing may occur.
  • Your account information may be rewritten.
  • If there is an EC site or payment site with OAuth, there is a possibility of financial damage as a result of the authentication information being stolen and the account information being rewritten. For example, you may suffer damage such as unfamiliar debt or shopping.
  • It is necessary to review the security settings of free mail and SNS on a regular basis.
  • In order to prevent damage such as spoofing with OAuth, it is important to properly set the security of free mail and SNS. There is a possibility that it will be an overwhelming situation that time is spent checking the security of free mail and SNS.

 

const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

    const GOOGLE_CLIENT_ID = 'our-google-client-id';

  const GOOGLE_CLIENT_SECRET = 'our-google-client-secret';

passport.use(new GoogleStrategy({

    clientID: GOOGLE_CLIENT_ID,

      clientSecret: GOOGLE_CLIENT_SECRET,

    callbackURL: "http://localhost:3000/auth/google/callback"

  },

  function(accessToken, refreshToken, profile, done) {

     

   userProfile=profile;

      return done(null, userProfile);

  }

));

 

app.get('/auth/google', 

     passport.authenticate('google', { scope : ['profile', 'email'] }));

 app.get('/auth/google/callback', 

       passport.authenticate('google', { failureRedirect: '/error' }),

   function(req, res) {

   // Successful authentication, redirect success.

      res.redirect('/success');

  });

 

 

5. Conclusion


Hopefully, the demo code and activities will help customers better understand the above method. In particular, user authentication is a function that benefits both users and website operators, but it also carries the risk of being abused. Both users and website operators will need to have a better understanding of Authentication/Authorization in order to use these features safely.

 

Have you ever been in charge of the Web but are not confident in your knowledge, want to improve your company's Web pages, but don't have the time or human resources? At Hachinet, we have been sincerely facing our customers and have been creating and renewing websites according to their needs. Please feel free to contact us.

 

 

If you are considering offshore development, please feel free to contact us.

※Here is our contact information.

Account Manager: Quan (Japanese/English available)

Phone number: (+84) 2462 900 388

Email: contact@hachinet.com

Please feel free to contact us for consultation/application by phone.

Click here for more information ▶