用JWT技術爲SpringBoot的API增長受權保護(轉),須要本身實現userdetailservice接口

轉自:https://blog.csdn.net/haiyan_qi/article/details/77373900

 

概述

示例 https://github.com/qihaiyan/jwt-boot-authjava

用spring-boot開發RESTful API很是的方便,在生產環境中,對發佈的API增長受權保護是很是必要的。如今咱們來看如何利用JWT技術爲API增長受權保護,保證只有得到受權的用戶纔可以訪問API。git

開發一個簡單的API

spring提供了一個網頁能夠便捷的生成springboot程序。github

如圖:在Search for dependencies中選擇H二、Web、Security、JPA,這幾個依賴在咱們的示例工程中會用到。web

spring-boot-starter-jwt

點擊Generate Project按鈕後,下載文件到本地。redis

在JwtauthApplication.java中增長一個方法:spring

@RequestMapping("/hello") @ResponseBody public String hello(){ return "hello"; }
  • 1
  • 2
  • 3
  • 4
  • 5

這樣一個簡單的RESTful API就開發好了。shell

如今咱們運行一下程序看看效果,打開命令行工具,執行:數據庫

cd jwtauth gradle bootRun
  • 1
  • 2

等待程序啓動完成後,能夠簡單的經過curl工具進行API的調用:json

curl http://localhost:8080/tasks
  • 1

至此,咱們的接口就開發完成了。可是這個接口沒有任何受權防禦,任何人均可以訪問,這樣是不安全的,下面咱們開始加入受權機制。api

增長用戶註冊功能

首先增長一個實體類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的合法性進行驗證。驗證的內容包括:

  1. 內容是一個正確的JWT格式

  2. 檢查簽名

  3. 檢查claims

  4. 檢查權限

處理登陸

建立一個類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數據。

相關文章
相關標籤/搜索