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

Administrator
发布于 2020-07-24 / 1179 阅读 / 0 评论 / 0 点赞

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

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>

评论