SpringSecurity的学习day01-简单的权限拦截

一、 pom.xml文件

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
</dependency>

二、 配置SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()//拦截请求
                .antMatchers("/auth/").permitAll() //permitAll是让所有人都可以访问
                .antMatchers("/auth/lv1/**").hasRole("VIP1")//过滤url
                .antMatchers("/auth/lv2/**").hasRole("VIP2")
                .antMatchers("/auth/lv3/**").hasRole("VIP3");
        http.formLogin();//没权限就跳转登陆,这是secrity自带的登陆页面和url,可用loginPage()自定义页面
        http.logout().logoutSuccessUrl("/auth");//注销方法,注销后默认跳转login?Logout,加logoutSuccessUrl("/auth")后是注销后跳转到/auth
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    /**inMemoryAuthentication表示从内存取账号密码*/
    /**passwordEncoder(new BCryptPasswordEncoder())
     *new BCryptPasswordEncoder().encode("123456")
     *添加密码加密方式,secrity5以上版本必须加,官方文档说的
    */
        auth
                .inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3");
    }
}

三、 简单的controller处理请求

@Controller
@RequestMapping("auth")
public class TestController {

    @RequestMapping
    public String welcome(){
        return "welcome";
    }

    @RequestMapping("/lv1/1")
    public String lv1(){
        return "vip1";
    }

    @RequestMapping("/lv2/2")
    public String lv2(){
        return "vip2";
    }

    @RequestMapping("/lv3/3")
    public String lv3(){
        return "vip3";
    }
}

4、 注销按钮

经过测试必须加thymeleaf且用相应的@{/logout}请求,不然会报错

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>wecomle</title>
</head>
<body>
<h1>所有人都可以访问的页面</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="注销">
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水豚少年的码农生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值