springsecurity的常规配置(SecurityConfig)

本文展示了如何在SpringSecurity配置中使用BCryptPasswordEncoder进行密码加密,并自定义JwtAuthenticationTokenFilter处理JWTtoken的验证。配置还包括关闭CSRF保护,无状态Session管理以及权限授权设置。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //创建BCyptPasswordEncoder并注入容器,就这样后面关于密码的验证就可以使用该格式加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired //自己设置的过滤器,用于检测头部是否有token,没有放行,有则从缓存中拿到数据再放行,该过滤器是 UsernamePasswordAuthenticationFilter
               //(已经是首个过滤器)的前面,
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    //SecurityConfig中一定要设置configure,其他基本是固定的,关闭跨域呀,关闭session呀,主要就是白名单会不一样
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }


    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值