1. 程式人生 > >輕鬆上手SpringBoot Security + JWT Hello World示例

輕鬆上手SpringBoot Security + JWT Hello World示例

## 前言 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/tea-flower.jpg) 在本教程中,我們將開發一個Spring Boot應用程式,該應用程式使用JWT身份驗證來保護公開的REST API。在此示例中,我們將使用硬編碼的使用者和密碼進行使用者身份驗證。 在下一個教程中,我們將實現Spring Boot + JWT + MySQL JPA,用於儲存和獲取使用者憑證。任何使用者只有擁有有效的JSON Web Token(JWT)才能使用此API。在之前的教程中,我們學習了[《什麼是JWT?》](https://iot.mushuwei.cn/#/what-jwt) 以及何時並如何使用它。 為了更好地理解,我們將分階段開發此專案: 1. 開發一個Spring Boot應用程式,該應用程式使用/hello路徑地址公開一個簡單的**GET** RESTAPI。 2. 為JWT配置Spring Security, 暴露路徑地址/authenticate **POST** RESTAPI。使用該對映,使用者將獲得有效的JSON Web Token。然後,僅在具有有效令牌的情況下,才允許使用者訪問API `/hello`。 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT/jwt-workflow.png) ## 搭建SpringBoot應用程式 ### 目錄結構 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/JWT-HelloWorld.jpg?imageMogr2/thumbnail/!75p) ### Pom.xml ```java org.springframework.boot spring-boot-starter-web ``` ### HelloWorld API ```java package iot.technology.jwt.without.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author james mu * @date 2020/9/7 19:18 */ @RestController @CrossOrigin public class HelloWorldController { @RequestMapping({ "/hello" }) public String hello() { return "Hello World"; } } ``` ### 建立bootstrap引導類 ``` package iot.technology.jwt.without; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author james mu * @date 2020/9/7 17:59 */ @SpringBootApplication(scanBasePackages = {"iot.technology.jwt.without"}) public class JwtWithoutJpaApplication { public static void main(String[] args) { SpringApplication.run(JwtWithoutJpaApplication.class, args); } } ``` 編譯並將JwtWithoutJpaApplication.java作為Java應用程式執行。在網頁輸入`localhost:8080/hello`。 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/jwt-postman.jpeg) ## Spring Security和JWT配置 我們將配置Spring Security和JWT來執行兩個操作 - 生成JWT---暴露**/authenticate**介面。傳遞正確的使用者名稱和密碼後,它將生成一個JSON Web Token(JWT)。 - 驗證JWT---如果使用者嘗試使用介面**/hello**,僅當請求具有有效的JSON Web Token(JWT),它才允許訪問。 ### 目錄結構 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/JWT-Complete-HelloWorld.jpg?imageMogr2/thumbnail/!75p) ### 生成JWT時序圖 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/withoutJpa-jwt1.png) ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/withoutJpa-jwt2.png) ### 驗證JWT時序圖 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/withoutJpa-jwt3.png) ### 新增Spring Security和JWT依賴項 ```java org.springframework.boot
spring-boot-starter-web
org.springframework.boot spring-boot-starter-security io.jsonwebtoken jjwt ``` 定義application.properties。正如在先前的JWT教程中所見,我們指定了用於雜湊演算法的金鑰。金鑰與標頭和有效載荷結合在一起以建立唯一的雜湊。如果您擁有金鑰,我們只能驗證此雜湊。 ``` jwt.secret=iot.technology ``` ### 程式碼剖析 JwtTokenUtil ```java package iot.technology.jwt.without.config; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; /** * @author james mu * @date 2020/9/7 19:12 */ @Component public class JwtTokenUtil implements Serializable { private static final long serialVersionUID = -2550185165626007488L; public static final long JWT_TOKEN_VALIDITY = 5*60*60; @Value("${jwt.secret}") private String secret; public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } public Date getIssuedAtDateFromToken(String token) { return getClaimFromToken(token, Claims::getIssuedAt); } public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public T getClaimFromToken(String token, Function claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Boolean ignoreTokenExpiration(String token) { // here you specify tokens, for that the expiration is ignored return false; } public String generateToken(UserDetails userDetails) { Map claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); } private String doGenerateToken(Map claims, String subject) { return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact(); } public Boolean canTokenBeRefreshed(String token) { return (!isTokenExpired(token) || ignoreTokenExpiration(token)); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } } ``` #### JWTUserDetailsService JWTUserDetailsService實現了Spring Security UserDetailsService介面。它會覆蓋loadUserByUsername,以便使用使用者名稱從資料庫中獲取使用者詳細資訊。當對使用者提供的使用者詳細資訊進行身份驗證時,Spring Security Authentication Manager呼叫此方法從資料庫中獲取使用者詳細資訊。在這裡,我們從硬編碼的使用者列表中獲取使用者詳細資訊。在接下來的教程中,我們將增加從資料庫中獲取使用者詳細資訊的DAO實現。使用者密碼也使用BCrypt以加密格式儲存。在這裡,您可以使用線上Bcrypt生成器為密碼生成Bcrypt。 ```java package iot.technology.jwt.without.service; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; /** * @author james mu * @date 2020/9/7 18:16 */ @Service public class JwtUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ("iot.technology".equals(username)) { return new User("iot.technology", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6", new ArrayList<>()); } else { throw new UsernameNotFoundException("User not found with username: " + username); } } } ``` #### JWTAuthenticationController 使用`JwtAuthenticationController`暴露**/authenticate**。使用Spring Authentication Manager驗證使用者名稱和密碼。如果憑據有效,則會使用JWTTokenUtil建立一個JWT令牌並將其提供給客戶端。 ```java package iot.technology.jwt.without.controller; import iot.technology.jwt.without.config.JwtTokenUtil; import iot.technology.jwt.without.model.JwtRequest; import iot.technology.jwt.without.model.JwtResponse; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.*; import java.util.Objects; /** * @author james mu * @date 2020/9/7 19:19 */ @RestController @CrossOrigin public class JwtAuthenticationController { private final AuthenticationManager authenticationManager; private final JwtTokenUtil jwtTokenUtil; private final UserDetailsService jwtInMemoryUserDetailsService; public JwtAuthenticationController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, UserDetailsService jwtInMemoryUserDetailsService) { this.authenticationManager = authenticationManager; this.jwtTokenUtil = jwtTokenUtil; this.jwtInMemoryUserDetailsService = jwtInMemoryUserDetailsService; } @RequestMapping(value = "/authenticate", method = RequestMethod.POST) public ResponseEntity createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception { authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); final UserDetails userDetails = jwtInMemoryUserDetailsService .loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } private void authenticate(String username, String password) throws Exception { Objects.requireNonNull(username); Objects.requireNonNull(password); try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (DisabledException e) { throw new Exception("USER_DISABLED", e); } catch (BadCredentialsException e) { throw new Exception("INVALID_CREDENTIALS", e); } } } ``` #### JwtRequest JwtRequest是儲存我們從客戶端收到的使用者名稱和密碼所必須的類。 ```java package iot.technology.jwt.without.model; import java.io.Serializable; /** * @author james mu * @date 2020/9/7 18:30 */ public class JwtRequest implements Serializable { private static final long serialVersionUID = 5926468583005150707L; private String username; private String password; //need default constructor for JSON Parsing public JwtRequest() { } public JwtRequest(String username, String password) { this.setUsername(username); this.setPassword(password); } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } } ``` #### JwtResponse 這是建立包含要返回給使用者的JWT響應所必須的類。 ```java package iot.technology.jwt.without.model; import java.io.Serializable; /** * @author james mu * @date 2020/9/7 19:11 */ public class JwtResponse implements Serializable { private static final long serialVersionUID = -8091879091924046844L; private final String jwttoken; public JwtResponse(String jwttoken) { this.jwttoken = jwttoken; } public String getToken() { return this.jwttoken; } } ``` #### JwtRequestFilter `JwtRequestFilter`繼承了Spring Web的`OncePerRequestFilter`類。對於任何傳入請求,都會執行此Filter類。它檢查請求是否具有有效的JWT令牌。如果它具有有效的JWT令牌,則它將在上下文中設定Authentication,以指定當前使用者已通過身份驗證。 ```java package iot.technology.jwt.without.config; import io.jsonwebtoken.ExpiredJwtException; import iot.technology.jwt.without.service.JwtUserDetailsService; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author james mu * @date 2020/9/7 19:14 */ @Slf4j @Component public class JwtRequestFilter extends OncePerRequestFilter { private final JwtUserDetailsService jwtUserDetailsService; private final JwtTokenUtil jwtTokenUtil; public JwtRequestFilter(JwtUserDetailsService jwtUserDetailsService, JwtTokenUtil jwtTokenUtil) { this.jwtTokenUtil = jwtTokenUtil; this.jwtUserDetailsService = jwtUserDetailsService; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final String requestTokenHeader = request.getHeader("Authorization"); String username = null; String jwtToken = null; // JWT Token is in the form "Bearer token". Remove Bearer word and get only the Token if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { jwtToken = requestTokenHeader.substring(7); try { username = jwtTokenUtil.getUsernameFromToken(jwtToken); } catch (IllegalArgumentException e) { log.error("Unable to get JWT Token"); } catch (ExpiredJwtException e) { log.error("JWT Token has expired"); } } else { logger.warn("JWT Token does not begin with Bearer String"); } //Once we get the token validate it. if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username); // if token is valid configure Spring Security to manually set authentication if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); usernamePasswordAuthenticationToken .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // After setting the Authentication in the context, we specify // that the current user is authenticated. So it passes the Spring Security Configurations successfully. SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } chain.doFilter(request, response); } } ``` #### JwtAuthenticationEntryPoint 此類繼承Spring Security的`AuthenticationEntryPoint`類,並重寫其`commence`。它拒絕每個未經身份驗證的請求併發送錯誤程式碼**401**。 ```java package iot.technology.jwt.without.config; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; /** * @author james mu * @date 2020/9/7 19:17 */ @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -7858869558953243875L; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } } ``` #### WebSecurityConfig 此類擴充套件了`WebSecurityConfigurerAdapter`,它為WebSecurity和HttpSecurity進行自定義提供了便捷性。 ```java package iot.technology.jwt.without.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * @author james mu * @date 2020/9/7 19:16 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; private final UserDetailsService jwtUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public WebSecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, UserDetailsService jwtUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint; this.jwtUserDetailsService = jwtUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // configure AuthenticationManager so that it knows from where to load // user for matching credentials // Use BCryptPasswordEncoder auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { // We don't need CSRF for this example httpSecurity.csrf().disable() // dont authenticate this particular request .authorizeRequests().antMatchers("/authenticate").permitAll(). // all other requests need to be authenticated anyRequest().authenticated().and(). // make sure we use stateless session; session won't be used to // store user's state. exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Add a filter to validate the tokens with every request httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } } ``` ## 程式碼演示 - 啟動Spring Boot應用程式 - 生成JSON Web Token(JWT) - 使用Url `localhost:8080/authenticate`建立POST請求。正文應具有有效的使用者名稱和密碼。在我們的情況下,使用者名稱是: iot.technology, 密碼是: password。 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/jwt-generate.jpg) - 驗證JSON Web Token(JWT) - 嘗試使用上述生成的令牌訪問Url localhost:8080/hello,如下所示 ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/jwt-validate.jpg) 專案原始碼: https://github.com/IoT-Technology/IOT-Technical-Guide/tree/master/IOT-Guide-JWT-Without-JPA ![](https://james-1258744956.cos.ap-shanghai.myqcloud.com/JWT-No-MySQL/%E5%85%AC%E4%BC%97%E5%8F%B7%E4%BF%A1%E6%81%