Spring Security的学习01

引入pom依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

 设置Spring Security的配置类 

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class securityConfigTest extends WebSecurityConfigurerAdapter {

    //注入UserDetailsService类对象用于密码的校验
    @Autowired
    private UserDetailsService userDetailsService;

    //注入数据源操作数据库
    @Autowired
    private DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
//        jdbcTokenRepository.setCreateTableOnStartup(true); 让Spring Security帮我们创建自动登录的记录表
        return jdbcTokenRepository;

    }

    //配置类继承后重写的方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());//调用我们设置的验证规则,和密码的加密方式
    }
    @Bean
    public PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登出后跳转页面
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").permitAll();
        //没有权限后的跳转页面403
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        //对于表单登录的跳转规则设置
        http.formLogin()
                .loginPage("/login.html")//未登录跳转到登录页面
                .loginProcessingUrl("/user/login")//Spring Security定义的登录接口
                .defaultSuccessUrl("/success.html").permitAll()//登陆成功之后跳转的路径
                .and().authorizeRequests()//请求授权
                .antMatchers("/","/test/hello","/user/login").permitAll()//对这些请求进行放行,一定要把登录成功后跳转的接口放行不然会死循环
//                .antMatchers("/test/index").hasAuthority("admin")
//                .antMatchers("test/index").hasAnyAuthority("admin,root")
                .antMatchers("/test/index").hasRole("sale")//为相应的路径分配权限,具有权限或者角色的就放行
                .anyRequest().authenticated()
                .and().rememberMe().tokenRepository(persistentTokenRepository())//自动登录的token验证
                .tokenValiditySeconds(60)//设置时长单位秒
                .userDetailsService(userDetailsService)
                .and().csrf().disable();

    }
}

 注解方式:

在配置类上加:

@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)

注解示例:

//    @Secured({"ROLE_sale","ROLE_manager"})
    @PreAuthorize("hasAnyAuthority('admin')")
    public String update (){
        return "update!!!";
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值