# 04.1-Security and DevOps Lesson1:Authentication and Authorization ###### tags: `Udacity` # 01 Introduction **Welcome!** **Motivation 1** Security is an essential aspect of a web application. There could be a variety of security breaches that can happen if the web application has not addressed these during the design and development phase. The diagram below describes some common security vulnerabilities: > Some Commom security vulnerabilities ![](https://i.imgur.com/ezxxmEF.png) To mitigate a few of the above-described security vulnerabilities, we need to incorporate a secure authentication and authorization mechanism in our web application. We will learn about a few authentication and authorization mechanisms, along with the implementation of JSON web token-based (JWT) authentication. **Motivation 2** Every software application evolves with time. This evolution is based on the needs of the customer and data-driven analysis of the software functionalities. The data-driven analysis is performed on the logs generated by the system. An enterprise web application generates a massive amount of raw data, such as application logs, server logs, network devices logs, IoT data, and many more. Therefore, we need a suitable depth of logging and an efficient tool to analyze the logs and need to learn about logging framework and the Splunk tool. **Motivation 3** The requirements of the customer are agile, as is the software development model. We need to follow these industry best-practices, which will increase the speed of software delivery and the speed of software evolution (enhancements). This requirement makes it essential to use DevOps model for “expeditious” software development. {%youtube pi7sa00tVws%} **Course Outline** In this course, you will learn about the technologies involved in the ”Security” and ”DevOps” of a Java-based enterprise application development. Here are the course objectives: You will be able to... - Explain the concepts related to authentication and authorization in an enterprise web application - Implement authentication and authorization on a Spring Boot application using JSON Web Token (JWT) - Demonstrate the fundamentals of unit testing using ”JUnit” and ”Mockito” frameworks - Describe SLF4J logging API and Log4J logging framework for code insight and debugging the application - Use ”Splunk” tool for analyzing machine-generated raw data - Use ”CI/CD” as one of the best practices of ”DevOps” In the first few lessons, you will learn fundamental concepts related to "**Security**". Then, you will discover the design of CI/CD as one of the best practices of ”**DevOps**”. Later in the course, we will introduce an “eCommerce application” that you will work through and submit as your final project. **Lesson Outline** We will start with **authentication** and **authorization** lesson to cover security. After completing this lesson you will be able to ... - Explain authentication and authorization - Explain authentication considerations and protection - Outline the hashing and salting techniques - Describe the Role-Based Access Control (RBAC) - Make use of JSON Web Tokens (JWTs) for authentication # 02 Authentication & Authorization **Why bother?** Data breaches are on the rise and are expensive. It is estimated that the amount of data stolen will triple in the next 5 years. The number of people affected rose 3 million from 2017 to 2018. The average cost of a single breach in the US has been estimated to be $7.9 million, and $3.8 million on average worldwide. Data breaches are becoming harder to track and locate.In 2018, the average amount of time to identify that a breach had occurred was 196 days. The more straightforward solution is to try to prevent breaches before they can occur; therefore, authentication and authorization are critical. {%youtube XZgBIIs2Qeg%} **What is Authentication?** Authentication confirms your identity. It is a process that proves that you are the person who you say you are. In the digital world, the most common way to authenticate is to use a username and password. For example, while logging into your eCommerce account, you prove your identity by providing an email and a password, sometimes followed by an OTP or a second factor. There are many other ways to authenticate, and these are depicted in the figure below. > Common Methods for Authentication ![](https://i.imgur.com/JWF5Q7A.png) **Common Mechanisms for Authentication** - **Token-based authentication** - an object you have or you control proves who you are (see https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication) (note: we do use this later in the form of JWT, but we first authenticate with the username and password, then sending the token on each subsequent request) - **OAuth** - is an industry-standard protocol for authorization that provides a token on your behalf once you’ve authenticated to the external service (see https://auth0.com/docs/protocols/oauth2 if you've ever seen a "Sign in with Google/Facebook/etc", this is likely done using OAuth) - **Time based token (TOTP)** - a token is generated with something only you know. This token changes after some time period (see https://www.freecodecamp.org/news/how-time-based-one-time-passwords-work-and-why-you-should-use-them-in-your-app-fdd2b9ed43c3/ This is very commonly used in Two Factor Authentication as the 2nd factor. If you have random codes you need to enter, they may have been generated using this scheme) - **Biometric authentication** such as Fingerprints or Facial recognition (popular on smartphones) **Network Authentication Protocols** Most of the standard mechanisms for authentication utilizes either of the following two "Network authentication protocols": i). Kerberos, and ii). Secure Sockets Layer (SSL) / Transport Layer Security (TLS). Kerberos provides secure authentication for client/server applications by using secret-key cryptography. Here are some links on Kerberos here. On the other hand, SSL/TLS uses a cryptographic system that uses two keys to encrypt data − a public key known to everyone and a private or secret key known only to the recipient of the message. A typical example is an HTTPS website that utilizes SSL/TLS certificate that is signed by a publicly trusted Certifying Authority. Here is a resource for SSL/TLS here. Details about these "Network authentication protocols" are beyond the scope of this lesson. {%youtube J6CfBpoUGj4%} **What is Authorization?** In general, Authorization comes after Authentication. Authorization determines whether you are permitted or have the right privilege to access the requested resources. In other words, it determines what a user is allowed to access. The following figure shows the order of execution of basic authentication and authorization in an application that follows the Model View Controller (MVC) architectural pattern. MVC is a way of organizing source code into three main categories - Model, View, and Controller. MVC helps in achieving loose coupling and high cohesion in the source code. MVC makes it easier to add new functionalities and changes without disturbing the existing code. The "Model" handles the data-related logic, "View" handles the user-interface related logic, the "Controller" handles the entire business logic such as processing the requests, and data manipulation. The Controller acts as an interface between the View and the Model. > Authentication 辨識你這個人 Authorization 授權給你這個人 ![](https://i.imgur.com/EuanFYu.png) # 03 Authentication Considerations **Authentication Considerations** Good authentication practices center around protecting the data used for authentication. You wouldn't just tell people your password, and so your website shouldn't either. You also need to ensure things are sufficiently random and complex, with things like length requirements, to ensure that your credentials aren't easily cracked. They must not be able to be forged easily, so no one can impersonate anyone else. Finally, they have to be deterministically generated, that is they must be generated the same way every time, to ensure you actually can authenticate users into your system. {%youtube NPIO7_4sZbg%} As referenced in the above video, you can check out the [OWASP](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Authentication_Cheat_Sheet.md) authentication cheatsheet for guidelines to authentication best practices. This is a great resource to check out now, or to bookmark for later reference. # 04 Authentication Protection **Authentication Protection** Imagine you have an application that must store users’ passwords. You might store them in a database, but storing them as is allows anyone to read them, if they can access your database, they can see your password. How can we solve this problem? We solve this with ”**hashing**”. **Hashing** is the process of generating a unique value (hash) for a given text, string, or numeric input (key). Unlike encryption-decryption, a good hash is irreversible. So, it is extremely difficult to compute the input given the output. If we do not use a good hashing algorithm, then an attacker may try to reverse the hash by brute-force, or exhaustive key search. Example: Let's take a hashing function that maps the input string to their length, as shown in the following table: ![](https://i.imgur.com/z6RoR5w.png) The string `CAT` would convert to 3, and the string `HAPPY` would map to 5. If you are given the output as 5, you would not be able to predict the actual input. Another point to note here is that two different inputs `HAPPY` and `LOGIC` are generating the same output, 5. Hence, the above example of hashing isn't a very good or secure hashing function. This illustration concludes the following two properties of hashing: - Hashing must be irreversible - Each input should have a unique output (or, practically, as close to unique as possible) A scenario, when a hash function gives the same output for different inputs, is called a collision. Let's explore more about hashing and collision next . {%youtube gVOyzxvY4Lw%} # 05 Hashing **What is Hashing?** **Hashing** is the process of generating a unique value (hash) for a given text, string, or numeric input (key). The generated value (hash) itself could be either text, string, or numeric, which depends upon the underlying **Hash** function. A **Hash** function is a one-way mathematical function which is used to generate a unique value for a given input. **Hashing is Irreversible** Let there be a function f, which can generate unique hash values for a given set of input. Another function g can get the original value back if the hash value is given as input. In such a case, the function f would be called reversible, as we can get the original value back. Hence, f cannot be used as a Hash function. Following is an example of a reversible function: > Whereas hashes are irreversible, so one cannot compute the input given the output. ![](https://i.imgur.com/oF0OXSx.png) **Where to use Hashing in an Application?** We use hashing to store any sensitive information in the system, such as user passwords. {%youtube zyRoz2ziTow%} > 影片只想表示Database存的是hash過的東西... Let's look at a simple example of hashing. Suppose that a user has the following password: `passw0rd`!. If we directly store this text in the database, we will have a major security vulnerability. - `passw0rd`! → database (⚠️ Bad idea! ⚠️) So instead, we can first run the password through a one-way function that produces a jumbled up piece of text (which has no obvious discernible relationship to the original password). That jumbled up piece of text is the hash, and it might look something like this: - `passw0rd`! → hash function → `@kdF3lkAWoLA` So when the client interacts with the server, rather than directly sending the password, the client can instead send the hash: - `passw0rd`! → hashing function → `@kdF3lkAWoLA` → stored in database This way, if someone gains access to the database, they will still not have access to the plain-text password. **Some famous Hashing Algorithms** There are many hashing algorithms prevalent in the industry. 1. MD5: The MD5 Message-Digest Algorithm is a hash function that accepts an input message of any length, and correspondingly produces a 128-bit (16-byte) hash value. Mostly, MD5 is used to verify data integrity. It was proposed by Ronal Rivest in 1992, as specified in RFC 1321. MD5 is comparatively unsafe, as it might get reversed by using brute-force-attack. Also, the chances of collision are very high in MD5. For non-critical applications, MD5 can be a good choice as it is computationally faster than other algorithms. > MD5 碰撞機率比較高,但是比較快,可是又沒有那麼安全因為可以被暴力解除(brute-force-attack)現在被業界禁止使用來對密碼加密 2. SHA: The SHA (Secure Hash Algorithm) is a set (SHA-0, SHA-1, SHA-2, and SHA-3) of cryptographic hash functions developed by the National Institute of Standards and Technology (NIST). In comparison to MD5, SHA generates secure hashes. SHA-1 is a 160-bit hash function. SHA-2 is further of two types: SHA-256 and SHA-512. SHA-256 is a 256-bit hash function that provides 128 bits of security in the case of collision attacks, while SHA-512 is a 512-bit hash function is designed for 256 bits of security. SHA-3 supports the same hash lengths as SHA-2. Chances of collision are high in SHA as well, but lesser than MD5. Thus, SHA-2 could be a good choice for general purpose application with a limited set of inputs, such as a University portal. > MD5是128bits, SHA是160bits,會collision但是比MD5好,有四種SHA, SHA-1,SHA-256,SHA-384,SHA-512業界普遍使用SHA-256 3. bCrypt: It is generally used to generate the hash for user-passwords. bCrypt is based on the Blowfish cipher algorithm. It has a crucial phase for key setup. This phase starts with encrypting a sub-key and uses the output of this encryption to change another sub-key. This way, the bCrypt involves iterative steps for generating the hash, making it a preferred choice of developers for critical applications. 4. sCrypt: It is a computationally intensive password-based key derivation function, proposed in 2016, as specified in RFC 7914. As part of the algorithm, it generates a large vector of pseudorandom bit strings. Thus, it requires a large amount of memory for computation. It isn't easy for a brute-force-attacker to reverse the hash, as it would involve a significantly high amount of time, memory, and a high number (billion) of attempts. Other password-based key derivation functions such as PBKDF1 and PBKDF2 have relatively low resource demands. **Deep Dive Topics to Explore Further** **Collision** In several scenarios, two different keys can generate the same hash. Such a scenario is called Collision. If we use a simple hash function, such as input length or sum of ASCII code of all characters, then it might lead to a collision. A collision can be resolved by using any of the following Collision Resolution Techniques: 1. Separate Chaining - It is a type of Open Hashing technique. The idea is to store the keys corresponding to collision (same) hash outputs in a Linked List. There would be a separate Linked List for each unique hash output. > 如果碰到collicion就用linked list來裝那些衝突的資料 3. Open Addressing - It is also called Closed Hashing. In this approach, for a given set of $n$ input keys, we take a data structure that can accommodate more than $n$ keys. The idea is to store the keys corresponding to collision (same) hash outputs in the next available slot in the data structure. 1. Linear or quadratic probing - Keep probing until an empty slot is found. 2. Double Hashing - We use two hash functions - one for hashing, and another for calculating the offset. Then, this offset is appended to the output of the first hash function. This way, the final output is expected to be collision-free value. The below diagram lists the approaches used for collision resolution. ![](https://i.imgur.com/Iyw6SJb.png) You may find it useful to read further about Collision Resolution Techniques [here](https://en.wikipedia.org/wiki/Hash_table#Collision_resolution). # 06 Salting **Salting** A salt is random data that is used as an additional input to a one-way function that "hashes" data, so that the final hash becomes more secure. Salting is an approach to generate two different hash values for two different users providing the same input. > 他主要的目的在不同的使用者如果用相同的密碼,加密之後的值也會不一樣 **A Sample Scenario to Depict the Need for Salting** Assume there are two users who might have the same password. For example, Alice and Bob, each with the password `m1p2s9wo@d`. According to a hash function, these two same input passwords would both map to a single output, say, `q#az5sd%!24`. Now, if the hash or corresponding password is compromised for one user, then the attacker would get access for another user as well. Salting then, prevents this by forcing each password to be unique in a way transparent to the user. > 如果兩個人的密碼不一樣但是hash出來的東西一樣的時候,只要其中一個人的密碼暴露了,另一個人的密碼也隨之暴露 {%youtube qfcENVs6Xks%} **How does Salting Works?** Following figure explains the concept of Salting: > A scenario to explain the need for Salting ![](https://i.imgur.com/ZNpw9C7.png) In the above example, two users have the same password: `m1p2s9wo@d`. Here's what happens if we run those passwords through a hash function: - User 1: `m1p2s9wo@d` → `hash(m1p2s9wo@d)` → `q#az5sd%!24` - User 2: `m1p2s9wo@d` → `hash(m1p2s9wo@d)` → `q#az5sd%!24` In the above case, we end up with the same hashed value for both users. But if we first add a salt, the result is different: - User 1: `m1p2s9wo@d` + `AE1USR` → `hash(m1p2s9wo@dAE1USR)` → `A#bz5AA%Z24` - User 2: `m1p2s9wo@d` + `BB2USR` → `hash(m1p2s9wo@dBB2USR)` → `B#bz5BB%Z48` As you can see, even though both users have the same original password, the hashes are different after salting. {%youtube Efh34cGDdVc%} **Points to Consider** 1. In a web application, the Salting must be done on the Server. 2. While hashing user-passwords, the Salt should be generated randomly. It is preferable if the Salt is unique for each user's password. 3. For numeric Salt, it is good to use secure algorithms such as Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) . Java has java.security.SecureRandom class for generating PRNG 3. For pseudo-random alpha-numeric string generator, you may use Apache class, as org.apache.commons.text.RandomStringGenerator 4. When we use Salting, there are two separate steps involved - (i) Generate the salted password, and (ii) Verify the salted password. We would see the detailed implementation in the project, where we would implement bCrypt hashing algorithm along with Salting. **Implementing Hashing (SHA) along with Salting:** In the following example, SHA-256 algorithm is used for hashing, and Salting is done by using an instance of `java.security.SecureRandom` class. For hashing, we can create an instance of `java.security.MessageDigest` to use any of the hashing algorithms SHA-1, SHA-256, SHA-512, or any other as mentioned here. ```java import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.MessageDigest; public class SaltExample { public static void main(String[] args)throws NoSuchAlgorithmException, NoSuchProviderException { String passwordToHash = "password"; byte[] salt = createSalt(); String securePassword = get_SecurePassword(passwordToHash, salt); System.out.println(securePassword); } // Method to generate the hash. //It takes a password and the Salt as input arguments private static String get_SecurePassword(String passwordToHash, byte[] salt){ String generatedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(salt); byte[] bytes = md.digest(passwordToHash.getBytes()); StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } generatedPassword = sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return generatedPassword; } // Method to generate a Salt private static byte[] createSalt() { SecureRandom random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); return salt; } } ``` Please note, if you wish to use bCrypt for hashing, you may use an instance of `org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder` class, which is a part of the Spring framework. We would see the implementation of bCrypt in our Spring Boot project. A sample snippet to understand the concept is given below: ```java BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); String securePassword = bCryptPasswordEncoder.encode("mySaltedPassword"); ``` In the above snippet, `securePassword` is the generated hash, and the `mySaltedPassword` is the String containing the actual password and the appended Salt. # 07 How to Pick a Good Hash Function **How to Pick a Good Hash Function** A good hash function needs to be efficiently computable, so it needs to be reasonably fast. It needs to be uniform, which means given an input the output needs to be as unique as possible. In other words, a low number of collisions exists. A given output should give absolutely no indication of its input. Inputs should be effectively random and uniformly distributed. Changing "cat" to "bat" should yield unpredictable results (this is known as the avalanche property) {%youtube xsRtyjq0Mjk%} > 影片只是說明bcrypt, scrypt, PBKDF2很適合使用,然後其中bcrypt重複hash了1024次,所以很難解開 # 08 Authorization - RBAC **Authorization** Authorization concerns itself with permission and rights. {%youtube fqTeO0JNGv4%} > 在說明Authorization的工作職責就是分辨不同的role給他相應的權限去取得某些資源~ **RBAC (Role-Based Access Control)** In the video, the Instructor mentioned that authorization is usually implemented as **Role-Based Access Control**, which is commonly abbreviated(縮寫) as RBAC. In RBAC, access is given based on a user's role—as a manager, engineer, customer service representative, etc. Permissions can then be given (and limited) to users based on their roles. That way, each type of user only has limited access—they are able to access only the specific things they need for their particular job. {%youtube ryR_3u1lt0w%} Authentication and authorization are different, yet related. You can't grant a right to a user (i.e., authorize that user) without first knowing who that user is (i.e., by authenticating their identity). > authorization: determining what a user is allowed to access > Authentication: Proving that you are the person you say you are. > RBAC: Permission are given to a group of users who all share the same role in the company. # 09 JWTs JSON Web Token (JWT) is an open standard [RFC 7519](https://tools.ietf.org/html/rfc7519), that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. - JWTs are used for authentication and authorization in Spring Boot applications. RESTful APIs provide this functionality (authentication and authorization). - REST is an acronym for REpresentational State Transfer. It is a software-architectural style, in which there is a stateless communication between client and server. - Stateless means that the server does not have to store the user cookies or other session data for any incoming request. Rather, the server authenticates a user based on JWT. - RESTful APIs help to keep clients and server independent from each other. This way, a client from any platform (Java, .net, PHP, Android, or any other) can communicate (or request a resource) to the server having REST API endpoints. > Usage of JWT for authentication and authorization ![Uploading file..._sgyjmhgt0]() The above diagram shows the usage of JWT for user authentication and authorization. A user can attempt to log in from any client. The server returns a JSON Web Token (JWT) upon successful validation of the user credentials. This JWT is then stored locally in the client. Later, when the user requests to access any protected resource, the server performs the JWT validation before granting access to the resource. This whole process is stateless, that the server does not store the user's session or cookies. {%youtube Ea8T8fXsZlc%} > JWT分成三個part,他被視為token的一種方式,這三個part分別是header, payload, signature. header主要放加密的方式以及token的type=jwt, payload主要放你的秘密,腳色是誰等等, 最後signature就是把header + payload做簽章`XXXX.VVVV.OOO` - What is stateless communication means? - Steteless communication means that the server does not have to store the user cookies or other session data for any incoming request. Rather, the server authenticates a user base on JWT. An example of a stateless protocol is HTTP, meaning that each request message can be understood in isolation. In contrast, a communication that requires keeping the internal state on the server is known as stateful communication. For example, a TCP connection-oriented session is a stateful connection because both systems maintain information about the session itself during its life. - A JWT can be used for Authorization and Authentication, but no hasing and salting. > Part Of The JWT - Header: Token type and the algorithm to be used in the signature - Claims: Payload - Signature: Encoded header, encoded payload, a secret, and the signing algorithm. # 10 Demo: eCommerce Starter **eCommerce Application Starter Code** In this next video, we'll walk through implementing JWTs in some starter code. We'll be working with the eCommerce application throughout this course, and then—at the end of the course—you'll finish and submit the application as your final project. You can find the link to the starter code for projects in this Nanodegree under the video—be sure to download it and follow along with the video in order to try implementing JWTs for yourself. **Step 1: Clone or Download the Project from GitHub to your local Computer** Following video tutorial demonstrates the steps required for Cloning a repository from GitHub. {%youtube Masbxs2NJnQ%} The repository for the eCommerce application starter code can be found at: https://github.com/udacity/JDND After cloning the repo, you can find the README and starter code in `projects/P04-eCommerce Application/starter_code.` **Step 2: Import the downloaded Project to IntelliJ IDE and Download Postman client** You need to import the locally-downloaded “P04-eCommerce Application” project to your IntelliJ IDE. Let's understand a few basic terminologies before proceeding ahead: - What is an Application and Web Server? - An application server is a compute system that processes requests and performs actions. In other words, the application server generates the dynamic (user-specific) content based on user-request. In our case, external users (across the internet) can connect to the eCommerce application server through a web-server that accepts the request for a particular "resource" and reverts with the "response". IntelliJ IDE has a built-in web server that can be used to preview and debug your application. This web server is always running and does not require any manual configuration. > An application server and a web server ![](https://i.imgur.com/22tl0ez.png) You can make sense of an API endpoint by understanding the next question. - What is the Postman client? - Postman is a client (a tool) that helps to test the RESTful APIs. RESTful APIs use request paths, types, and bodies to perform a specific action, such as creating a user or modifying a cart associated with an existing user. Postman client can be downloaded from https://www.getpostman.com/downloads/. Once you start the application server and open the Postman client, you can make requests and receive a response. Postman is a useful tool to issue and save requests. Postman can create GET, PUT, POST, etc. requests complete with bodies. - What is an API endpoint? - Postman is used to test API endpoints automatically. The API endpoint is a URL that is used to make a specific request to the server. Let's look at an example of an API endpoint: ![](https://i.imgur.com/H5gnLF7.png) We can add additional information to an endpoint to return a specific response. In the case of a successful response, the Postman client will display `200 OK` status. This endpoint can be accessed in the Postman as shown in the snapshot below: ![](https://i.imgur.com/P6WWCy8.png) Let's test your understanding of API endpoints. Assume the following data is available in the database of your application. Use this information to answer the questions that follow: ![](https://i.imgur.com/LSsy1Pe.png) For retrieving the data of the first 3 users, you would have to use `GET http://localhost:8080/api/user/limit=3`. And, if you make a `POST` request, you'd get a 200 OK response, if successful. Let's see a code walkthrough in the IntelliJ IDE and making requests in Postman API Development Environment {%youtube 8RjUWi5BTlc%} **Step 3: Code walkthrough in the IntelliJ IDE and making requests in Postman API Development Environment - 2** {%youtube UXN9DWkNmlE%} **Step 4: Making addToCart and submitOrder requests in Postman API Development Environment** {%youtube gp-xtgquzfA%} # 11 Demo: Authentication and Authorization using JWT {%youtube lwCAIem7jqQ%} {%youtube ycKpZyZosq4%} For the link on JWT implementation referenced in the video, click [here](https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/). **Conclusion** We have achieved the following objectives, as promised at the beginning of this lesson: - Explicate authentication and authorization - Explain authentication considerations and protection - Outline the hashing and salting techniques - Describe the Role-Based Access Control (RBAC) - Make use of JSON Web Tokens (JWTs) for authentication # 12 DEPRECATED eCommerce Starter Code eCommerce Starter Code {%youtube RdtlZ1kwf-c%} The repository for the eCommerce application starter code can be found at: https://github.com/udacity/JDND After cloning the repo, you can find the README and starter code in `projects/P04-eCommerce Application/starter_code`. We'll be working with the eCommerce application throughout this course, and then—at the end of the course—you'll finish and submit the application as your final project. So the more familiar you get with it now, the easier that final project will be! # 補充01 : Token-base authentication > 為甚麼要去使用tokens? - 因為他是無狀態且是可擴展的server - 可攜性也高 - 可以傳authentication給其他application - extra security? > 誰會去使用token? - API or Web application - ex. FaceBook, Twriiter, GitHub... > Why Tokens Came Around? - Server Based Authentication(The Traditional Method) - 因為Http協定是Stateless無法記住使用者,必須重新取得authentication一次,如果要寄主user是誰就需要把他們登入的資料存在server的內部記憶體 - 但是它有幾個缺點 1. Sessions: 每次user要去認證的時候server就需要生成session,會造成server的負擔 2. Scalability (擴充): 因為sessions通常都次存在server的in-memory,但現在是雲上世界!!所以這樣的儲存方式會阻礙擴充性 3. CORS (Cross-Origin Resource Sharing): 如果想要在不同的設備上傳輸,當使用[AJAX](https://tw.alphacamp.co/blog/ajax-asynchronous-request)從別的地方去取得resources可能會被forbidden requests. 4. [CSRF](https://blog.techbridge.cc/2017/02/25/csrf-introduction/) (Cross-site request forgery) - How Token Based Works? - Token是存放在client那哩,每次發送request的時候token就會放在request的header裡面,當server收到就會去檢查token,所以token的可攜性很高。因為存放在client那裏所以token也是無狀態的。 # 補充02: 密碼的儲存要用哪一種演算法? 參考:https://www.qa-knowhow.com/?p=4334 其實最安全的主要有三個PBKDF2, SCrypt, Bcrypt,但這三個都運算很慢需要用到大量的記憶體,所以我覺得還是使用SHA-256或是PBKDF2就好了。 1. MD5 - 最廢但也最快 3. SHA - MD5是128bits, SHA是160bits,會collision但是比MD5好,有四種SHA, SHA-1,SHA-256,SHA-384,SHA-512業界普遍使用SHA-256 4. PBKDF2, SCrypt, Bcrypt - 比較好,PBKDF2有被美國NIST跟FIPS標準推薦使用比較有公信力 ![](https://i.imgur.com/qAVPQbq.png) # 補充03: