WebSecurity配置

本文介绍了一个Spring Security的安全配置类,详细解释了如何通过注解配置HTTP安全策略,包括路径权限控制、认证需求及CSRF防御禁用等。此外,还展示了如何使用BCryptPasswordEncoder进行密码加密。
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author Administrator
 * @desc  安全配置类
 */
@Configuration
//@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * authorizeRequests:所有security全注解配置实现的开端,表示开始说明需要的权限
     * 需要的权限分为两个部分,第一个部分是拦截的路径,第二部分是访问该路径需要的权限
     * antMatchers 拦截的路径 permitall()所有权限都可以,直接放行所有hasAnyRole()这个方法可以指定角色
     * anyRequest 任何请求   anthenticated需要认证后才能访问
     *  .and().csrf().disable(); 固定写法  使csrf攻击失效
     *  如果不设置为disabled,所有除了内部的请求,其余外部请求都被认为是在攻击我这个网站,全部拦截
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }

    /**
     * 将BCryptPasswordEncoder类注入进工程(使用Bcrypt加密方式)
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值