navigation
[react] Hooks
[Encapsulation 01- Design Pattern] Design principles and factory pattern (simple abstract approach) Adapter pattern Decorator pattern [Encapsulation 02- Design Pattern] Command pattern Enjoy pattern Composite pattern Agent pattern
[React from zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose Deploy React + Egg +nginx+mysql [React From zero practice 05- background] Gitlab-CI using Docker automated deployment
[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend
[source -vue06] Vue. NextTick and VM.$nextTick [Deployment 01] Nginx [Deployment 02] Docker deployVUE project [Deployment 03] Gitlab-CI
[Data Structures and Algorithms 01] Binary search and sort
[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise Data Structures and Algorithms – Binary Search and Sorting Js Design Patterns – Agents, policies, singletons
/ front-end learn java01 – SpringBoot combat environment configuration and the HelloWorld service [front-end learn java02 – SpringBoot combat] mybatis + mysql implementation song to add and delete [front-end learn java03 – SpringBoot combat] Lombok, log, Java04 -SpringBoot combat deployment [front-end science Java04 -SpringBoot combat] static resources + interceptor + front and back end file upload [front-end science Java05 -SpringBoot combat] common annotates + Redis implementation statistics function [front-end science Java06 -SpringBoot combat] inject + Swagger2 3.0 + unit test JUnit5 [Front-End science Java07 -SpringBoot real World] IOC scanner + transaction + Jackson [front-end science Java08 -SpringBoot real world summary 1-7 [java09-SpringBoot] Multi-module configuration + Mybatis-plus + single multi-module package deployment [Java10 -SpringBoot] Bean assignment conversion + parameter verification + global exception handling [Java11-SpringSecurity] configuration + memory + database = three ways to achieve RBAC [java12-SpringSecurity] JWT
(1) Pre-knowledge
(1) Some words
Signature bearer bearer // organise organise interval interval poll // Polling interval Brand color Calendar calendar algorithm amount VerifyCopy the code
(2) Traditional session authentication
- Session authentication process
- 1. The user submits the user name and password to the server
- 2. After the server is authenticated, click
session
Save related data, such as user name, role, login time, etc - 3. The server returns a
session_id
And writecookie
- 4. The client
Every subsequent request
, will carrycookie
, that is,session_id
Return server - 5. The server receives the packet
session_id
To findPreviously saved data
, from which the identity of the user is known
- Sesstion is just an object
cookie <-> sessionId <-> session
- disadvantages
- The cluster service
- Cross domain
- csrf
- Poor scalability: If it is (cluster service), or if it is (cross-domain), then session sharing is required (each server must be able to read the session)
- If cookies are used to carry information, CSRF attacks may occur
- The test code
@RestController public class TestSessionController { @GetMapping("/session") public String getSession( @requestparam ("username") String username, HttpServletRequest request) { Will store (session_id) into (cookie) and will carry the cookie on every request, Cookie: (JSESSIONID) request.getSession().setAttribute("username", username); Return "Server session saved successfully "; }}Copy the code
(3) Base64URL
- The JWT algorithm for header and payload (stringed) is (base64URL)
- As a token, JWT may in some cases be placed in a URL (e.g
api.example.com/?token=xxx
)+ / =
It has a special meaning in the URL so it has to be replaced with one of the following three algorithms, which is base64URL- = => Is omitted
- Plus => is replaced by minus
- / => is replaced with _
(4) cookie to review
- Definition: A cookie is a small piece of text stored in the browser
- Size: The size of each cookie is generally not
- Main Role of cookie
- 1. Determine whether the two requests came from the consent server
- 2. Save some status information
- The contents of a cookie
- The name of the cookie
- The value of the cookie, in which is (the real number)
- Due to the time
- Domain name – The default is the current domain name
- Effective path – mo throw is the current url
The browser cannot accept cookies or send cookies to the server
- How do I check whether cookies are opened in the browser?
window.navigator.cookieEnabled
- How do I return the cookie of the current page?
document.cookie
- Conditions for sharing cookies?
- As long as (domain name) and (port) are the same, it does not need to be the same protocol
- Cookies set on a.com can also be shared on a.com
- HTTP response =====> Cookie generation【【set-cookie】】
- The server saves cookies in the browser and places the set-cookie field in the HTTP response header
- If you have more than one
set-cookie
Field indicates that multiple cookies are set to be saved in the browser - In addition to the value of the cookie, you can set other properties
- HTTP request =====> Cookie sending 【【cookie】】
- (cookie field) can contain (multiple cookies), use (;) segmentation
- How to change the cookie set previously ????????
- All four conditions must be met at the same time, that is, all four must match, as long as one value is different, the cookie will be regenerated
- key
- domain
- path
- secure
- All four conditions must be met at the same time, that is, all four must match, as long as one value is different, the cookie will be regenerated
- When a server receives a cookie, there are two things it doesn’t know
- Cookie attributes, such as expiration time
- Which domain name sets the cookie, the first level domain name or the second level domain name
- The attribute of the cookie
- Expires Max-Age
- Expires
- Expires specifies a specific expiration time, in UTC format
- If (Expires is not set) or (Expires is set to null) it is equivalent to (session), which means that when the browser window closes and the session ends, the cookie will be deleted
- The browser decides whether the cookie is expired based on (local time)
- Max-Age
- Represents the number of seconds the cookie exists from now on
- If set-cookie does not specify Expires or max-age, it is session-cookie
- Domain
- The Domain attribute specifies which domains to attach the Cookie to when the browser makes HTTP requests
- If this property is not specified, the browser defaults to the level 1 domain name of the current URL
- If the server specifies a domain name in the set-cookie field that is not part of the current domain name, the browser will reject the Cookie
- Path
- The Path attribute specifies which paths to attach the Cookie to when the browser makes HTTP requests
- Secure/ safety/security
- The Secure attribute specifies that the browser can only send this Cookie to the server under the HTTPS encryption protocol
- HttpOnly
- The HttpOnly attribute specifies that the Cookie cannot pass
JavaScript
The script to get the- mainly
Document. The cookie properties
The XMLHttpRequest object
Request API
- I can’t get that property
- The HttpOnly attribute specifies that the Cookie cannot pass
(5) Calendar and Date
(1) instantiate Date Date = new Date(); Calendar calendar = Calendar.getInstance(); log.info("calendar{}", calendar.toString()); log.info("date{}", date.toString());Copy the code
SimpleDateFormat = new SimpleDateFormat(" YYYY-MM-DD hh: MM :ss"); Date date = dateFormat.parse("2020-02-02 02:20:20"); String format = dateFormat.format(date); log.info("format{}", format); String parse2 = dateFormat.format(new Date()); log.info("parse2{}", parse2); Calendar instance = Calendar.getInstance(); instance.setTime(date); Date time = instance.getTime(); log.info("time{}", time);Copy the code
(6) ( jackson – ObjectMapper
(map) and (object) and (JSON) conversion
- Use Jackson to do this
- map object json
- new ObjectMapper()
writeValueAsString
=> Convert various types to JSONreadValue
=> Convert json to various valuesconvertValue
=> Conversion of various values
@SpringBootTest @Slf4j public class JwtTest { @Test public void object2map() throws JsonProcessingException { JwtUserBean jwtUserBean = new JwtUserBean(1, "admin", "admin", "admin"); // bean HashMap<String, Object> stringObjectHashMap = new HashMap<>(); stringObjectHashMap.put("a", "a"); stringObjectHashMap.put("b", "b"); // object => json ObjectMapper objectMapper = new ObjectMapper(); // jackson => ObjectMapper String s = objectMapper.writeValueAsString(jwtUserBean); // writeValueAsString() log.info("object => json: {}", s); // map => json ObjectMapper objectMapper1 = new ObjectMapper(); // jackson => ObjectMapper String s1 = objectMapper1.writeValueAsString(stringObjectHashMap); // writeValueAsString() log.info("map => json: {}", s1); // json => object ObjectMapper objectMapper3 = new ObjectMapper(); // jackson => ObjectMapper JwtUserBean jwtUserBean1 = objectMapper3.readValue(s, JwtUserBean.class); log.info("json => object: {}", jwtUserBean1); // json => map ObjectMapper objectMapper4 = new ObjectMapper(); // jackson => ObjectMapper Map map = objectMapper4.readValue(s1, Map.class); log.info("json => map: {}", map); // object => map !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ObjectMapper objectMapper5 = new ObjectMapper(); // jackson => ObjectMapper Map map1 = objectMapper5.convertValue(jwtUserBean, Map.class); log.info("object => map: {}", map); }}Copy the code
(2) the JWT
- JWT
- JWT is
json web tokens
The abbreviation of - The server is no longer saving sessions, that is, the server is stateless
- JWT is
(1) Data structure of JWT
- JWT behaves as a long string, using (
.
) Divide into three paragraphs- The header in the head
- Payload load
- Signature signature
header.payload.signature
- header
- Header is a JSON object
- There are two properties in the header object
alg
typ
- Alg Indicates the signature algorithm => The default value is yes
hs256
- Typ indicates the type of the token => Generally
JWT
{ "alg": "HS256", "typ": "JWT" } Copy the code
- payload
- Payload is also a JSON object that holds the actual data that needs to be passed
- Note: JWT is unencrypted by default and can be read by anyone, so do not put secret information in this section
- signature
-
Signature is the signature of the first two parts to prevent string changes
-
(2) Storage of JWT
- It can be stored either in a cookie or in a localStorage
- When sending a request, it is best to place it in
header
Header, you can put it in cookies but you can’t cross domainsAuthorization: Bearer <token>
(3) Use of JWT in SpringBoot
(3.1) Install dependencies
<! -- JWT --> <dependency> <groupId>com.auth0</groupId> <artifactId> Java -jwt</artifactId> <version>3.15.0</version> </dependency>Copy the code
Generate JWT (3.2)
@RestController @Slf4j public class JwtTest { @GetMapping("/jwt-test") public void testJwt() throws ParseException { HashMap<String, Object> HeaderMap = new HashMap<>(); Calendar instance = Calendar.getInstance(); instance.add(Calendar.SECOND, 2000); // 2000s would not run out of money. // 2000s would not run out of money. // 2000s would not run out of money. // 2000s would not run out of money. "woow_wu7") // ------ payload .withClaim("age", 20) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - content. WithExpiresAt (the instance. The getTime ()) / / expiration time sign (Algorithm. HMAC256 (" secretXx ")); // ---------------- signature log.info("token: {}", token); }Copy the code
Verify the JWT (3.3)
Public class JwtTest {@getMapping ("/jwt-test") public void testJwt() public class JwtTest {@getMapping ("/jwt-test") public void testJwt() Throws ParseException {// 1. JWT encryption HashMap<String, Object> HeaderMap = new HashMap<>(); Calendar instance = Calendar.getInstance(); instance.add(Calendar.SECOND, 2000); // 2000s would not run out of money. // 2000s would not run out of money. // 2000s would not run out of money. // 2000s would not run out of money. "woow_wu7") // ------ payload .withClaim("age", 20) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - content. WithExpiresAt (the instance. The getTime ()) / / expiration time sign (Algorithm. HMAC256 (" secretXx ")); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - signature signature means algorithm (algorithm) the info (" token: {} ", token); // 2. JWT validation // secretXx generate validation object // Note: Algorithm.hmac256 () takes the signature string JWTVerifier secretXx = that was passed in when the JWT was generated JWT.require(Algorithm.HMAC256("secretXx")).build(); DecodedJWT verify = secretXx.verify(token); String username = verify.getClaim("username").asString(); Integer age = verify.getClaim("age").asint (); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- through the token, obtain the age the info (" incoming token authentication token of username: {} ", username); Log.info (" Pass token, verify token age:{}", age); Date expiresAt = verify.getExpiresAt(); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- through the token, obtain the expiration time info (" token of expiration time: {} ", expiresAt); }}Copy the code
(3.4) JWT Common exception information
SignatureVerificationException -- -- -- -- -- - signature inconsistencies exception - TokenExpiredException -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- token is abnormal - date AlgorithmMismatchException -- -- -- -- -- -- -- -- -- -- algorithm does not match the exception, algorithm means algorithm - InvalidClaimException -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the failure of payloadCopy the code
(3.5) Encapsulation of JWT
Public class JwtUtil {/ / private said can only access, and other children can't visit / / static static class, said the class itself to access / / final said a derived class, Private static final String SIGNATURE = "randomString!" ; // Token => header.payload. Signature public static String getToken(Map<String, Object> map) {// Calendar Instance = Calendar.getInstance(); instance.add(Calendar.DATE, 7); // ------------ Expiration time. JWTCreator.Builder Builder = jwt.create (); // ----------------- jwt map.forEach((k, v) -> { builder.withClaim(String.valueOf(k), String.valueOf(v)); // jwt payload }); String Token = Build.withexPiresat (instance.getTime()) // ----------------- JWT Expiration time .sign(Algorithm.HMAC256(SIGNATURE)); // ---------------- jwt signature return token; } // JWT verify + obtain information // Verify token validity, Public static DecodedJWT verify(String token) {DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token); return verify; // Return verify.getClaim() to obtain the payload in (token)}}Copy the code
(3.6) Use of JWT in SpringBoot
Public class jwtLogAdd Controller {// If the service is an interface implemented by an implementation class, I will take on an Add controller. Here is injected into interface @autowired JwtLoginTestServiceInterface JwtLoginTestServiceInterface; @GetMapping("/jwt-login") public Object getJwtUser( @RequestParam String username, @RequestParam String password ) { HashMap<Object, Object> stringObjectHashMap = new HashMap<>(); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the result map Object jwtUser = jwtLoginTestServiceInterface. GetJwtUser (username, password); // ---- object, query database return value Map Map = new ObjectMapper().convertValue(jwtUser, map.class); //-------------------- object => map String token = JwtUtil.getToken(map); // Generate token try {stringobjecthashMap. put(" MSG ", "request succeeded "); stringObjectHashMap.put("token", token); } catch (Exception e) {stringobjecthashMap. put(" MSG ", "request failed "); stringObjectHashMap.put("data", e.getMessage()); } return stringObjectHashMap; }}Copy the code
(2) Access interface, do token verification, whether expire, @test private Map<String, Object> testToken2() {HashMap<String, Object> stringObjectHashMap = new HashMap<>(); try { JwtUtil.verify("\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6ImFkbWluIiwicm9sZXMiOiJhZG1pbiIsImlkIjoiMSIsImV4c CI6MTYyMzU3MTU5MywidXNlcm5hbWUiOiJhZG1pbiJ9.JNME8wbaedF1EYyr9agbTs9pmTxkQ8Iwxh0WJB1Zwig\""); Stringobjecthashmap. put(" MSG ", "request succeeded "); return stringObjectHashMap; } the catch (SignatureVerificationException e) {/ / -- -- -- -- -- -- -- -- - signature error e.p rintStackTrace (); } the catch (TokenExpiredException e) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- expired e.p rintStackTrace (); } the catch (AlgorithmMismatchException e) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- algorithm does not match the e.p rintStackTrace (); } the catch (InvalidClaimException e) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- invalid content e.p rintStackTrace (); } stringobjecthashmap. put(" MSG ", "request failed "); return stringObjectHashMap; }Copy the code