SpringBoot整合SpringSecurity

SpringSecurity是一个安全框架,主要用于授权和认证,在普通项目中,我们使用过滤器和拦截器也可以实现,但是使用SpringSecurity更加简单。

项目搭建

1、新建项目,导入依赖

<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.2.3.RELEASEversion>
parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
dependencies>

2、新建配置文件,关闭thymeleaf的缓存

server:
  port: 9000
spring:
  thymeleaf:
    cache: false

3、编写静态页面

resources/templates/index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>indextitle>
head>
<body>
<form action="">
    <h1><a href="/level1/index">level1a>h1>
    <h1><a href="/level2/index">level2a>h1>
    <h1><a href="/level3/index">level3a>h1>
form>
body>
html>

resources/templates/level1/index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>level1title>
head>
<body>
<h1>level1h1>
body>
html>

resources/templates/level2/index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>level2title>
head>
<body>
<h1>level2h1>
body>
html>

resources/templates/level3/index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>level2title>
head>
<body>
<h1>level2h1>
body>
html>

4、编写Controller

package com.qianyu.controller;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class RouterController {
    @GetMapping({"/", "index", "index.html"})
    public String index() {
        return "index";
    }

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

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

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

5、编写启动类

package com.qianyu;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

6、此时访问http://localhost:9000,所有的页面均可正常访问

整合SpringSecurity

1、导入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-securityartifactId>
dependency>

2、新建配置类

package com.qianyu.config;

import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.crypto.bcrypt.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 添加请求授权规则
        http.authorizeRequests()
                // 首页所有人都可以访问
                .antMatchers("/").permitAll()
                // level1下的所有请求,vip1用户才能访问
                .antMatchers("/level1/**").hasRole("vip1")
                // level2下的所有请求,vip2用户才能访问
                .antMatchers("/level2/**").hasRole("vip2")
                // level3下的所有请求,vip3用户才能访问
                .antMatchers("/level3/**").hasRole("vip3");
        // 开启登录页面,即没有权限的话跳转到登录页面,对应地址:/login
        http.formLogin();
        // 开启注销功能
        http.logout()
                // 注销之后跳转到首页
                .logoutSuccessUrl("/");
        // 开启记住我功能,默认保存两周,底层使用cookie机制实现
        http.rememberMe();
    }

    // 认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 在新版本的SpringSecurity中新增了许多加密方法,不使用加密的话就会出现异常
        // 这个例子模拟的是内存中的用户,真正开发中我们可以使用数据库
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("12345")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("qianyu").password(new BCryptPasswordEncoder().encode("12345")).roles("vip1", "vip2")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("12345")).roles("vip1");
    }
}

3、此时,再次访问的话,会跳转到登录界面(这个登录界面是SpringSecurity默认提供的登录界面)

SpringBoot整合SpringSecurity_第1张图片

登录之后,不同权限的用户可以访问不同的页面

4、注销功能

注销功能默认使用/logout请求处理。所以,我们在resources/templates/index.html页面添加一个注销按钮


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>indextitle>
head>
<body>
<form action="">
    <h1><a href="/level1/index">level1a>h1>
    <h1><a href="/level2/index">level2a>h1>
    <h1><a href="/level3/index">level3a>h1>
    <h1><a href="/logout">注销a>h1>
form>
body>
html>

此时,登录之后再点击注销,就会弹出注销页面:

SpringBoot整合SpringSecurity_第2张图片

注销之后,再点击跳转的话,需要再次登录

整合thymeleaf

现在我们的主界面是这个样子的:

SpringBoot整合SpringSecurity_第3张图片
我们希望的是,用户登录之后,只能看到自己有权限访问的页面。即页面会根据登录与否、以及用户权限动态改变。

1、引入依赖

<dependency>
    <groupId>org.thymeleaf.extrasgroupId>
    <artifactId>thymeleaf-extras-springsecurity5artifactId>
dependency>

2、在resources/templates/index.html中进行设置

注意导入xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"才能有提示


<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>indextitle>
head>
<body>
<form action="">
    
    <h1 sec:authorize="hasRole('vip1')"><a href="/level1/index">level1a>h1>
    <h1 sec:authorize="hasRole('vip2')"><a href="/level2/index">level2a>h1>
    <h1 sec:authorize="hasRole('vip3')"><a href="/level3/index">level3a>h1>
    
    <div sec:anthorize="isAuthenticated()">
        <h1>
            用户名:<span sec:authentication="name">span>
            <a href="/logout">注销a>
        h1>
    div>
    
    <div sec:anthorize="!isAuthenticated()">
        <h1>
            <a href="/login">登录a>
        h1>
    div>
form>
body>
html>

此时,再次登录,页面就会根据不同用户展示不同内容

自定义页面

前面我们的登录页面都是使用的SpringSecurity默认的,我们可以在配置类中修改成我们自定义的登录页面

1、自定义登录页面

resources/templates/login.html

这里的name属性默认是usernamepassword,这里我们采用自定义的方式,/login是SpringSecurity默认的处理登录的Controller


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>logintitle>
head>
<body>
<form action="/login" method="post">
    用户名:<input type="text" name="user"><br>
    密码:<input type="password" name="pwd"><br>
    <input type="radio" name="remember">记住我
    <button type="submit">提交button>
form>
body>
html>

2、修改SecurityConfig配置类

configure(HttpSecurity http)方法中添加如下内容,(注意这里我们要禁止csrf,否则登录会被拦截):

// 开启登录页面,即没有权限的话跳转到登录页面,对应地址:/login
http.formLogin()
        // 登录页面
        .loginPage("/toLogin")
        // 用户名的name
        .usernameParameter("user")
        // 密码的name
        .passwordParameter("pwd")
        // 处理登录的Controller
        .loginProcessingUrl("/login");
http.csrf().disable();
// 开启记住我功能,默认保存两周
http.rememberMe()
        // name属性
        .rememberMeParameter("remember");

3、编写Controller

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

此时,我们就可以使用自定义登录页面了

SpringSecurity使用的AOP的思想,我们在不用修改原来代码的基础上就可以实现原有代码功能的增强

你可能感兴趣的:(java高级)