【Spring Security系列】Spring Security整合JWT:构建安全的Web应用
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.web.authentication.UsernamePasswordAuthenticationFilter;
import com.example.security.jwt.JwtAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 禁用 CSRF
.csrf().disable()
// 不通过Session进行认证
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// 对于所有请求都需要认证
.authorizeRequests().anyRequest().authenticated()
.and()
// 添加自定义的JWT认证过滤器
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
这段代码演示了如何在Spring Security中整合JWT(Json Web Token)认证机制。首先,我们定义了一个JwtAuthenticationFilter
的Bean,然后在configure(HttpSecurity http)
方法中,我们禁用了CSRF保护,设置了会话管理策略为无状态(STATELESS),对所有请求都需要认证,并且添加了自定义的JWT认证过滤器,将其置于Spring Security默认的UsernamePasswordAuthenticationFilter之前。这样,我们就可以在Spring Security的框架下,使用JWT来保护我们的Web应用了。
评论已关闭