SpringSecurity整合JWT的使用示例
Spring Security是一個強(qiáng)大的安全性框架,它提供了許多強(qiáng)大的功能來保護(hù)應(yīng)用程序,而JWT(JSON Web Token)是一種用于在網(wǎng)絡(luò)環(huán)境中傳遞聲明的開放標(biāo)準(zhǔn)。
整合Spring Security和JWT,可以使我們的應(yīng)用程序更加安全和高效。下面是整合步驟:
添加Spring Security和JWT的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
配置Spring Security
在Spring的配置類中,我們需要設(shè)置一些安全配置,包括:
- 配置安全規(guī)則
- 配置JWT過濾器
- 配置認(rèn)證管理器
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
"/swagger-resources/**",
"/swagger-ui.html",
"/v2/api-docs",
"/webjars/**"
};
@Autowired
private JwtFilter jwtFilter;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers("/api/authenticate").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
配置JWT
@Configuration
public class JwtConfig {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long expiration;
@Bean
public JwtEncoder jwtEncoder() {
return new JwtEncoder(secret, expiration);
}
@Bean
public JwtDecoder jwtDecoder() {
return new JwtDecoder(secret);
}
}
實(shí)現(xiàn)自定義UserDetailsService
我們需要提供一個實(shí)現(xiàn)了UserDetailsService接口的自定義類,用于從數(shù)據(jù)庫中獲取用戶信息。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
}
}
實(shí)現(xiàn)JwtEncoder和JwtDecoder
我們需要提供一個JwtEncoder和JwtDecoder類,用于創(chuàng)建和驗(yàn)證JWT。
public class JwtEncoder {
private final String secret;
private final long expiration;
public JwtEncoder(String secret, long expiration) {
this.secret = secret;
this.expiration = expiration;
}
public String createToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", userDetails.getUsername());
claims.put("iat", new Date());
claims.put("exp", new Date(System.currentTimeMillis() + expiration));
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
}
public class JwtDecoder {
private final String secret;
public JwtDecoder(String secret) {
this.secret = secret;
}
public String getUsernameFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return true;
} catch (SignatureException e) {
LOGGER.error("Invalid JWT signature - {}", e.getMessage());
} catch (MalformedJwtException e) {
LOGGER.error("Invalid JWT token - {}", e.getMessage());
} catch (ExpiredJwtException e) {
LOGGER.error("Expired JWT token - {}", e.getMessage());
} catch (UnsupportedJwtException e) {
LOGGER.error("Unsupported JWT token - {}", e.getMessage());
} catch (IllegalArgumentException e) {
LOGGER.error("JWT claims string is empty - {}", e.getMessage());
}
return false;
}
}
實(shí)現(xiàn)JWT過濾器
我們需要提供一個JwtFilter類,用于過濾JWT。
@Component
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtDecoder jwtDecoder;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (StringUtils.isBlank(header) || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
String token = header.replace("Bearer ", "");
if (jwtDecoder.validateToken(token)) {
String username = jwtDecoder.getUsernameFromToken(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
}
至此,我們已經(jīng)成功地整合了Spring Security和JWT。更多相關(guān)SpringSecurity整合JWT內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringSecurity+Redis+Jwt實(shí)現(xiàn)用戶認(rèn)證授權(quán)
- springboot+springsecurity+mybatis+JWT+Redis?實(shí)現(xiàn)前后端離實(shí)戰(zhàn)教程
- SpringBoot3.0+SpringSecurity6.0+JWT的實(shí)現(xiàn)
- SpringBoot整合SpringSecurity和JWT和Redis實(shí)現(xiàn)統(tǒng)一鑒權(quán)認(rèn)證
- SpringBoot+SpringSecurity+jwt實(shí)現(xiàn)驗(yàn)證
- SpringSecurity詳解整合JWT實(shí)現(xiàn)全過程
- mall整合SpringSecurity及JWT認(rèn)證授權(quán)實(shí)戰(zhàn)下
- mall整合SpringSecurity及JWT實(shí)現(xiàn)認(rèn)證授權(quán)實(shí)戰(zhàn)
- Java SpringSecurity+JWT實(shí)現(xiàn)登錄認(rèn)證
- springSecurity+jwt使用小結(jié)
相關(guān)文章
Java實(shí)現(xiàn)ATM系統(tǒng)超全面步驟解讀建議收藏
這篇文章主要為大家詳細(xì)介紹了用Java實(shí)現(xiàn)簡單ATM機(jī)功能,文中實(shí)現(xiàn)流程寫的非常清晰全面,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
MyBatis參數(shù)處理與查詢結(jié)果映射實(shí)例詳解
本文給大家介紹MyBatis參數(shù)處理與查詢結(jié)果映射的問題,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2026-03-03
Spring?JDBC配置與使用的實(shí)現(xiàn)
本文主要介紹了Spring?JDBC配置與使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-06-06
Spring Security 技術(shù)原理與實(shí)戰(zhàn)全解析
SpringSecurity是Spring生態(tài)的安全框架,提供認(rèn)證、授權(quán)、攻擊防護(hù)等功能,基于過濾器鏈和上下文模型,支持可插拔架構(gòu)與聲明式安全控制,適用于分布式和云原生場景,是Java應(yīng)用安全的核心解決方案,本文給大家介紹Spring Security 原理實(shí)戰(zhàn),感興趣的朋友一起看看吧2025-06-06

