您好,登錄后才能下訂單哦!
在Spring Boot中集成JWT(JSON Web Token)進(jìn)行身份驗(yàn)證是一個(gè)常見(jiàn)的需求。以下是一個(gè)基本的步驟指南,幫助你實(shí)現(xiàn)這一功能。
首先,在你的pom.xml
文件中添加必要的依賴:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<!-- Other dependencies -->
</dependencies>
創(chuàng)建一個(gè)JWT過(guò)濾器來(lái)處理JWT的驗(yàn)證和生成。
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
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;
import java.util.Base64;
public class JwtRequestFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final String secretKey = "yourSecretKey"; // Replace with your secret key
public JwtRequestFilter(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
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 {
Claims claims = Jwts.parser().setSigningKey(Base64.getDecoder().decode(secretKey)).parseClaimsJws(jwtToken).getBody();
username = claims.getSubject();
} catch (Exception e) {
// handle exception
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (!jwtToken.equals(Jwts.builder().setSubject(userDetails.getUsername()).signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, secretKey).compact())) {
// handle unauthorized access
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
filterChain.doFilter(request, response);
}
}
配置Spring Security以使用JWT過(guò)濾器。
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add JWT filter
http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Configure user details service
auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtRequestFilter jwtRequestFilter() {
return new JwtRequestFilter();
}
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
// Implement your UserDetailsService here
return new CustomUserDetailsService();
}
}
實(shí)現(xiàn)一個(gè)UserDetailsService
來(lái)加載用戶信息。
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;
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Implement your logic to load user details from database
// For example:
return new User(username, "password", new ArrayList<>());
}
}
創(chuàng)建一個(gè)控制器來(lái)生成JWT令牌。
import io.jsonwebtoken.Jwts;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JwtController {
private final String secretKey = "yourSecretKey"; // Replace with your secret key
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password) {
// Implement your logic to authenticate user
if ("user".equals(username) && "password".equals(password)) {
return Jwts.builder()
.setSubject(username)
.signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, secretKey)
.compact();
} else {
throw new RuntimeException("Invalid username or password");
}
}
}
以上步驟涵蓋了在Spring Boot中集成JWT進(jìn)行身份驗(yàn)證的基本流程。你需要根據(jù)實(shí)際需求調(diào)整代碼,例如實(shí)現(xiàn)真正的用戶認(rèn)證邏輯、處理異常等。希望這些信息對(duì)你有所幫助!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。