Spring Security

使用

导入依赖

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

编写配置类

授权

  • 固定模板
 @EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}
  • 编写规则
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
    // 授权规则
    http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/lev1/**").hasAnyRole("vip1")
            .antMatchers("/lev2/**").hasAnyRole("vip2")
            .antMatchers("/lev3/**").hasAnyRole("vip3");
    
    // 没权限进入自定义的登录界面,usernameParameter、passwordParameter接收前端的name
    http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/toLogin");

    // 关闭防止csrf功能 解决注销退出报错
     http.csrf().disable();

    // 注销,注销成功跳转到首页
    http.logout().logoutSuccessUrl("/");

    // 开启记住我设置cookie
    http.rememberMe().rememberMeParameter("remember");
}
<form th:action="@{/toLogin}" method="post">
    <input name="username" type="text" placeholder="用户名"/>
    <input name="password" type="password" placeholder="密码"/>
    <input type="checkbox" name="remember"/>记住我
    <button type="submit">登录</button>
</form>

认证

  • 编写规则
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 为用户添加角色权限,有对应权限的用户可以访问对应的路由
    // 密码需要加密
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
            .and()
            .withUser("diana").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

整合thymeleaf

  • 导入依赖
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
  • 引入命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
  • 判断
<!-- 如果没登录显示登录按钮 -->
<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/toLogin}">登录</a>
</div>
<!-- 如果已登录显示注销和用户名-->
<div sec:authorize="isAuthenticated()">
    用户名:<span sec:authentication="name"></span>
    <a th:href="@{/logout}">注销</a>
</div>
<!-- 拥有对应权限的用户登录后显示对应的模块 -->
<div sec:authorize="hasRole('vip1')">
    <a th:href="@{/lev1/1}">lev1-1</a>
    <a th:href="@{/lev1/2}">lev1-2</a>
    <a th:href="@{/lev1/3}">lev1-3</a>
</div>
<div sec:authorize="hasRole('vip2')">
    <a th:href="@{/lev2/1}">lev2-1</a>
    <a th:href="@{/lev2/2}">lev2-2</a>
    <a th:href="@{/lev2/3}">lev2-3</a>
</div>
<div sec:authorize="hasRole('vip3')">
    <a th:href="@{/lev3/1}">lev3-1</a>
    <a th:href="@{/lev3/2}">lev3-2</a>
    <a th:href="@{/lev3/3}">lev3-3</a>
</div>

代码

  • login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form th:action="@{/toLogin}" method="post">
    <input name="username" type="text" placeholder="用户名"/>
    <input name="password" type="password" placeholder="密码"/>
    <input type="checkbox" name="remember"/>记住我
    <button type="submit">登录</button>
</form>
</body>
</html>
  • index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            border:3px solid #000
        }
    </style>
</head>
<body>
<!-- 如果没登录显示登录按钮 -->
<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/toLogin}">登录</a>
</div>
<!-- 如果已登录显示注销和用户名-->
<div sec:authorize="isAuthenticated()">
    用户名:<span sec:authentication="name"></span>
    <a th:href="@{/logout}">注销</a>
</div>

<!-- 拥有对应权限的用户登录后显示对应的模块 -->
<div sec:authorize="hasRole('vip1')">
    <a th:href="@{/lev1/1}">lev1-1</a>
    <a th:href="@{/lev1/2}">lev1-2</a>
    <a th:href="@{/lev1/3}">lev1-3</a>
</div>
<div sec:authorize="hasRole('vip2')">
    <a th:href="@{/lev2/1}">lev2-1</a>
    <a th:href="@{/lev2/2}">lev2-2</a>
    <a th:href="@{/lev2/3}">lev2-3</a>
</div>
<div sec:authorize="hasRole('vip3')">
    <a th:href="@{/lev3/1}">lev3-1</a>
    <a th:href="@{/lev3/2}">lev3-2</a>
    <a th:href="@{/lev3/3}">lev3-3</a>
</div>
</body>
</html>
  • RouterController
package com.diana.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author diana
 * @create 2020-09-13 19:20
 */
@Controller
public class RouterController {

    @GetMapping({"/","/index"})
    public String index(){
        return "index";
    }

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

    @GetMapping("/lev1/{id}")
    public String lev1(@PathVariable("id") String id){
        return "lev1/"+id;
    }

    @GetMapping("/lev2/{id}")
    public String lev2(@PathVariable("id") String id){
        return "lev2/"+id;
    }

    @GetMapping("/lev3/{id}")
    public String lev3(@PathVariable("id") String id){
        return "lev3/"+id;
    }
}

  • SecurityConfig
package com.diana.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;

/**
 * @author diana
 * @create 2020-09-13 19:38
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/lev1/**").hasAnyRole("vip1")
                .antMatchers("/lev2/**").hasAnyRole("vip2")
                .antMatchers("/lev3/**").hasAnyRole("vip3");

        // 没权限进入自定义的登录界面,usernameParameter、passwordParameter接收前端的name
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/toLogin");

        // 关闭防止csrf功能 解决注销退出报错
         http.csrf().disable();

        // 注销,注销成功跳转到首页
        http.logout().logoutSuccessUrl("/");

        // 开启记住我设置cookie
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 为用户添加角色权限
        // 密码需要加密
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("diana").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.diana</groupId>
    <artifactId>spring-boot-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值