SpringSecurity使用

这里写一下SpringSecurity官网的常用操作,主要结合Thymeleaf来实现用户登录过滤和权限管理来描述其应用。基于 Idea 操作。

首先明确SpringSecurty主要用来干什么的?
认证 (你是谁)
授权 (你能干什么)
攻击防护 (防止伪造身份)
其核心就是一组过滤器链,项目启动后将会自动配置。最核心的就是 Basic Authentication Filter 用来认证用户的身份,一个在spring security中一种过滤器处理一种认证方式。使用这个包可以简化用户的认证授权等

这个例程实现的功能:

使用Spring Secuity的一些主要功能进行测试,实现页面上不同用户权限的显示和访问,理解Spring Security的基本运用,想探究详细原理,可以看官方文档

1 引入Spring Security meaven依赖文件
<!-- security依赖 -->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--        thymeleaf security 整合包-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

2 基础程序

项目目录
在这里插入图片描述
在这里插入图片描述

controller层

@Controller
public class TestController {
    @RequestMapping({"/","/index"})
    public String toIndex(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        //System.out.println("adfasfd");
        return "login";
    }
    @RequestMapping("/level1/{id}")
    public String toLevel1(@PathVariable("id")int id){
        return "view/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String toLevel2(@PathVariable("id")int id){
        return "view/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String toLevel3(@PathVariable("id")int id){
        return "view/level3/"+id;
    }

}

前端页面—index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<!--xmlns:sec 这个命名空间可以不填写 但是写页面的时候不会有错误提示-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Welcome to Index
<div sec:authorize="isAuthenticated()">
    <a href="/logout">注销</a>
</div>
<div sec:authorize="isAuthenticated()">
    <a href="/index">主页
        用户名:<span sec:authentication="name"></span>
<!--        角色:<span sec:authentication="principal.getAuthorities()"></span>-->
    </a>
</div>
<div sec:authorize="!isAuthenticated()">
    <a href="/toLogin">登录</a>
</div>
<hr>
<div sec:authorize="hasRole('vip1')">
    <h1>level1:</h1>
    <a href="level1/1">level1_1</a>
    <a href="level1/2">level1_2</a>
    <a href="level1/3">level1_3</a>
</div>
<div sec:authorize="hasRole('vip2')">
<hr>
    <h1>level2:</h1>
    <a href="level2/1">level2_1</a>
    <a href="level2/2">level2_2</a>
    <a href="level2/3">level2_3</a>
</div>
<div sec:authorize="hasRole('vip3')">
    <hr>
    <h1>level3:</h1>
    <a href="level3/1">level3_1</a>
    <a href="level3/2">level3_2</a>
    <a href="level3/3">level3_3</a>
</div>
</body>
</html>

前端 login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/toLogin}" th:method="post">
    <div>
        <label>用户名</label>
        <input type="text" name="username" placeholder="Username">
    </div>
    <div>
        <label>密码</label>
        <input type="password" name="password" placeholder="Password">
    </div>
    <div>
        <input type="checkbox" name="remeber"> 记住我
        <button>提交</button>
    </div>
</form>

</body>
</html>

前端页面----level ***.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>level*_*.html</h1>
</body>
</html>

config层

package com.lyy.demo.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;

//AOP
@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("/toLogin");
        //注销开启
        http.csrf().disable();//关闭csrf功能 登陆失败存在的原因
        http.logout().logoutSuccessUrl("/toLogin");
       // super.configure(http);
        //开启记住我
        http.rememberMe().rememberMeParameter("remeber");
    }
    //认证:Springboot2.1 可用
    //在Spring security 5.0+ 新增了加密方式 不加密会有PasswordEncoder 问题
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2").and()
                .withUser("root")
                .password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3").and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip3");
    }
}

以上程序是在 Spring Boot 2.0.9版本中测试的,可以通过,如果版本过高,Thymeleaf和Spring Security的整合包会出问题,谨慎使用,仅供参考!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值