SpringSecurity学习笔记

点击下载源码

1.环境搭建

1.1项目创建

在这里插入图片描述
在这里插入图片描述
目录结构
在这里插入图片描述
添加thymeleaf依赖

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

1.2 创建Controller

package com.tamy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class SecurityController {
//    要记得添加Thymeleaf依赖,不然就会报错,Path[/index]
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "pages/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "pages/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "pages/level3/"+id;
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

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

2.用户认证与授权

2.1 SecurityConfig

package com.tamy.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会跳转到登录页面
        http.formLogin();
    }

//    密码编码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");
    }
}

3.注销与权限控制

3.1SecurityConfig 接上面的程序

package com.tamy.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会跳转到登录页面
        http.formLogin().loginPage("/login");

        http.logout().logoutSuccessUrl("/");

        //防止网站攻击:post   get
        http.csrf().disable();  //关闭csrf功能,注销失败存在的原因,默认是开启的

		//记住我功能
        //firefox失败,不能成功保存cookie,关闭浏览器,cookie自动删除
        http.rememberMe().rememberMeParameter("remember");
    }

//    密码编码

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据应该从数据库中读取,现在是在内存中模拟账号
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");
    }
}

3.2导入依赖

<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
</dependency>

3.3index.html 首页

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">

<!--      thymeleaf的命名空间:
            xmlns:th="http://www.thymeleaf.org"

          thymeleaf-extras-springsecurity5的命名空间:
            xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"


-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <h1>SpringSecurity</h1>
<!--    如果未登录,显示登录按钮-->
    <div sec:authorize="!isAuthenticated()">
        <a th:href="@{/login}">登录</a>
    </div>
<!--    如果登录,显示注销按钮-->
    <div sec:authorize="isAuthenticated()">
        <a th:href="@{/logout}">注销</a>
    </div>
    <hr>

	<!-- 登陆的用户只有拥有vip1的权限才显示 -->
    <div sec:authorize="hasRole('vip1')">
        <span>vip1</span>
        <a href="/level1/1">vip1.html</a>
    </div>
    <hr>
    <!-- 登陆的用户只有拥有vip2的权限才显示 -->
    <div sec:authorize="hasRole('vip2')">
        <span>vip2</span>
        <a href="/level2/1">vip2.html</a>
    </div>
    <hr>
    <!-- 登陆的用户只有拥有vip3的权限才显示 -->
    <div sec:authorize="hasRole('vip3')">
        <span>vip3</span>
        <a href="/level3/1">vip3.html</a>
    </div>
    <hr>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值