轉自:https://blog.csdn.net/haiyan_qi/article/details/77373900
概述
示例 https://github.com/qihaiyan/jwt-boot-auth
用spring-boot開發RESTful API非常的方便,在生產環境中,對發布的API增加授權保護是非常必要的。現在我們來看如何利用JWT技術為API增加授權保護,保證只有獲得授權的用戶才能夠訪問API。
開發一個簡單的API
spring提供了一個網頁可以便捷的生成springboot程序。
如圖:在Search for dependencies中選擇H2、Web、Security、JPA,這幾個依賴在我們的示例工程中會用到。
點擊Generate Project按鈕后,下載文件到本地。
在JwtauthApplication.java中增加一個方法:
@RequestMapping("/hello") @ResponseBody public String hello(){ return "hello"; }
- 1
- 2
- 3
- 4
- 5
這樣一個簡單的RESTful API就開發好了。
現在我們運行一下程序看看效果,打開命令行工具,執行:
cd jwtauth gradle bootRun
- 1
- 2
等待程序啟動完成后,可以簡單的通過curl工具進行API的調用:
curl http://localhost:8080/tasks
- 1
至此,我們的接口就開發完成了。但是這個接口沒有任何授權防護,任何人都可以訪問,這樣是不安全的,下面我們開始加入授權機制。
增加用戶注冊功能
首先增加一個實體類MyUser:
package com.example.jwtauth; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class MyUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String username; private String password; public long getId() { return id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
然后增加一個Repository類MyUserRepository,可以讀取和保存用戶信息:
package com.example.jwtauth; import org.springframework.data.jpa.repository.JpaRepository; public interface MyUserRepository extends JpaRepository<MyUser, Long> { MyUser findByUsername(String username); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
得益於SpringDataJpa,只需要定義一個interface,就讓我們擁有了數據的CRUD功能。由於我們在build.gradle中引入了H2,所以我們擁有了一個本地數據庫,不需要做任何配置,springboot就會使用這個數據庫,不得不說springboot確實極大的減輕了開發工作量。
下面增加一個類UserController,實現用戶注冊的接口:
package com.example.jwtauth; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { private MyUserRepository applicationUserRepository; private BCryptPasswordEncoder bCryptPasswordEncoder; public UserController(MyUserRepository myUserRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.applicationUserRepository = myUserRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @PostMapping("/signup") public void signUp(@RequestBody MyUser user) { user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); applicationUserRepository.save(user); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
其中的
@PostMapping("/signup")
- 1
這個方法定義了用戶注冊接口,並且指定了url地址是/users/signup。由於類上加了注解 @RequestMapping(“/users”),類中的所有方法的url地址都會有/users前綴,所以在方法上只需指定/signup子路徑即可。
密碼采用了BCryptPasswordEncoder進行加密,我們在Application中增加BCryptPasswordEncoder實例的定義。
@SpringBootApplication @RestController public class JwtauthApplication { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } // ...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
增加JWT認證功能
用戶填入用戶名密碼后,與數據庫里存儲的用戶信息進行比對,如果通過,則認證成功。傳統的方法是在認證通過后,創建sesstion,並給客戶端返回cookie。現在我們采用JWT來處理用戶名密碼的認證。區別在於,認證通過后,服務器生成一個token,將token返回給客戶端,客戶端以后的所有請求都需要在http頭中指定該token。服務器接收的請求后,會對token的合法性進行驗證。驗證的內容包括:
-
內容是一個正確的JWT格式
-
檢查簽名
-
檢查claims
-
檢查權限
處理登錄
創建一個類JWTLoginFilter,核心功能是在驗證用戶名密碼正確后,生成一個token,並將token返回給客戶端:
package com.example.jwtauth; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; public JWTLoginFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException { try { MyUser user = new ObjectMapper() .readValue(req.getInputStream(), MyUser.class); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), new ArrayList<>()) ); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { String token = Jwts.builder() .setSubject(((User) auth.getPrincipal()).getUsername()) .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000)) .signWith(SignatureAlgorithm.HS512, "MyJwtSecret") .compact(); res.addHeader("Authorization", "Bearer " + token); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
該類繼承自UsernamePasswordAuthenticationFilter,重寫了其中的2個方法:
attemptAuthentication
:接收並解析用戶憑證。
successfulAuthentication
:用戶成功登錄后,這個方法會被調用,我們在這個方法里生成token。
授權驗證
用戶一旦登錄成功后,會拿到token,后續的請求都會帶着這個token,服務端會驗證token的合法性。
創建JwtAuthenticationFilter類,我們在這個類中實現token的校驗功能。
package com.example.jwtauth; import io.jsonwebtoken.Jwts; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; public class JwtAuthenticationFilter extends BasicAuthenticationFilter { public JwtAuthenticationFilter(AuthenticationManager authManager) { super(authManager); } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { chain.doFilter(req, res); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(req); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); } private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { String token = request.getHeader("Authorization"); if (token != null) { // parse the token. String user = Jwts.parser() .setSigningKey("MyJwtSecret") .parseClaimsJws(token.replace("Bearer ", "")) .getBody() .getSubject(); if (user != null) { return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); } return null; } return null; } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
該類繼承自BasicAuthenticationFilter,在doFilterInternal方法中,從http頭的Authorization
項讀取token數據,然后用Jwts包提供的方法校驗token的合法性。如果校驗通過,就認為這是一個取得授權的合法請求。
SpringSecurity配置
通過SpringSecurity的配置,將上面的方法組合在一起。
package com.example.jwtauth; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; private BCryptPasswordEncoder bCryptPasswordEncoder; public MyWebSecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userDetailsService = userDetailsService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable().authorizeRequests() .antMatchers(HttpMethod.POST, "/users/signup").permitAll() .anyRequest().authenticated() .and() .addFilter(new JWTLoginFilter(authenticationManager())) .addFilter(new JwtAuthenticationFilter(authenticationManager())); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
這是標准的SpringSecurity配置內容,就不在詳細說明。注意其中的
.addFilter(new JWTLoginFilter(authenticationManager()))
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
這兩行,將我們定義的JWT方法加入SpringSecurity的處理流程中。
下面對我們的程序進行簡單的驗證:
# 請求hello接口,會收到403錯誤 curl http://localhost:8080/hello # 注冊一個新用戶 curl -H "Content-Type: application/json" -X POST -d '{ "username": "admin", "password": "password" }' http://localhost:8080/users/signup # 登錄,會返回token,在http header中,Authorization: Bearer 后面的部分就是token curl -i -H "Content-Type: application/json" -X POST -d '{ "username": "admin", "password": "password" }' http://localhost:8080/login # 用登錄成功后拿到的token再次請求hello接口 # 將請求中的XXXXXX替換成拿到的token # 這次可以成功調用接口了 curl -H "Content-Type: application/json" \ -H "Authorization: Bearer XXXXXX" \ "http://localhost:8080/hello"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
總結
至此,給SpringBoot的接口加上JWT認證的功能就實現了,過程並不復雜,主要是開發兩個SpringSecurity的filter,來生成和校驗JWT token。
JWT作為一個無狀態的授權校驗技術,非常適合於分布式系統架構,因為服務端不需要保存用戶狀態,因此就無需采用redis等技術,在各個服務節點之間共享session數據。