springSecurity

在web开发中,安全第一位。

我们在servlet中使用过滤器、拦截器也可以做到安全的功能,框架会更方便简单一点。

做网站:安全应该在设计之初就考虑!

  • 漏洞,会泄露隐私
  • 架构一旦确定,后期再考虑安全的问题就很麻烦

shiro、springSecurity:两者很像。他们都可以做认证和授权的功能。

code

这个有个唯一的缺点就是springboot版本实在是太老了。

  • 用户认证和授权
  • 注销及权限控制
  • 记住我及首页定制
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>
<!--
    spring-boot-starter-parent当前版本的mvn源
    https://maven.aliyun.com/repository/central
  -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecurity</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
<!--        springsecurity-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
<!--
    security thymeleaf整合包
    在thymeleaf中写一些关于springSecurity的操作
-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </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>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
        </dependency>
    </dependencies>

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

</project>
yaml 复制代码
spring:
  thymeleaf:
    cache: false
html 复制代码
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>

<!--未登录-->
<div sec:authorize="isAuthenticated()">
    <!--已登录:用户名 注销-->
    用户名:<span sec:authentication="name"></span>
    角色:<span sec:authentication="principal.authorities"></span>
    <a href="/logout">注销</a>
</div>


<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/toLogin}">登录</a>
</div>


<!--动态菜单功能,根据用户的角色动态实现-->
<!--<div sec:authentication="hasRole('vip1')"></div>-->


</body>
</html>
html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>

<form th:action="@{/toLogin}" method="post">
    username:<input type="text" name="username">
    password:<input type="password" name="password">
    <input type="checkbox" name="remember-me"> 记住我
    <input type="submit" value="登录">
</form>
</body>
</html>
java 复制代码
package com.example.springsecurity.controller;

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

@Controller
public class RouterController {

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



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

    @RequestMapping({"/level1/{id}"})
    public String level1(@PathVariable("id") Integer id){
        return "level1/" + id;
    }

    @RequestMapping({"/level2/{id}"})
    public String level2(@PathVariable("id") Integer id){
        return "level2/" + id;
    }

    @RequestMapping({"/level3/{id}"})
    public String level3(@PathVariable("id") Integer id){
        return "level3/" + id;
    }
}
java 复制代码
package com.example.springsecurity.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");


        // 开启登录功能,没有权限默认到登录页面,默认会找 /login
		// springSecurity提供了默认的登录页面
        http.formLogin().loginPage("/toLogin").successForwardUrl("/index");

        /**
        // 登录页面为/toLogin 如果想指定登录的请求路径为login 前端登录的请求路径也得改为login
        // .loginProcessingUrl("/login")

        // 请求登录默认的用户名和密码的 name为 username 和 password
        // 如果前端指定的为user和pwd,后端接收也必须改
        // .usernameParameter("user").passwordParameter("pwd")
         */

        // 自定义接收前端的参数
//        .usernameParameter("user").passwordParameter("pwd");
        // 开启注销功能,默认会找 /logout
        http.logout()
//                .logoutUrl();
        .logoutSuccessUrl("/index");

        // 关闭csrf功能
        // csrf 跨站请求伪造
        http.csrf().disable();
        
        // 开启记住我功能 cookie实现,默认保存两周
        // 自定义接收前端的参数
        http.rememberMe();
        // 默认的请求参数为remember-me
//                .rememberMeParameter("remember");


    }


    // 认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 真实场景下肯定是要连接数据库的,在这里我们把用户信息绑定到内存中来测试
        // passwordEncoder 密码必须被加密,不可以明文
        auth.inMemoryAuthentication().passwordEncoder(encoder)
                .withUser("ks").password(encoder.encode("123")).roles("vip1","vip3")
                .and()
                .withUser("root").password(encoder.encode("123")).roles("vip2");


        // jdbc 方式,没测试过
        // @Autowared
        // private Datasource datasource
//        User.UserBuilder users = User.withDefaultPasswordEncoder();
//        auth.jdbcAuthentication()
//                .dataSource(datasource)
//                .withDefaultSchema()
//                .withUser(users.username("user").password("password").roles("user"))
//                .withUser(users.username("admin").password("password").roles("user","admin"));
    }
}

满是沥青味道的下雨天,絮状云闪耀的大晴天,飞沙走石的大风天,每天我都搭乘着拥挤的电车前往学校。打工也在继续,偶尔还会和奥寺前辈同一天轮班。我尽可能地直视她,努力挤出笑脸,若无其事地和她交谈。

我强行让自己对每个人都表现得一视同仁。

你的名字

新海诚

部分内容转载自:

https://www.bilibili.com/video/BV1PE411i7CV?p=35\&spm_id_from=pageDriver\&vd_source=64c73c596c59837e620fed47fa27ada7

相关推荐
haciii1 天前
Spring Boot启动源码深度分析 —— 新手也能看懂的原理剖析
spring boot
泉城老铁1 天前
Spring Boot对接抖音获取H5直播链接详细指南
spring boot·后端·架构
后端小张2 天前
基于飞算AI的图书管理系统设计与实现
spring boot
考虑考虑3 天前
Jpa使用union all
java·spring boot·后端
阿杆3 天前
同事嫌参数校验太丑,我直接掏出了更优雅的 SpEL Validator
java·spring boot·后端
昵称为空C4 天前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
麦兜*4 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*4 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
汤姆yu4 天前
基于springboot的毕业旅游一站式定制系统
spring boot·后端·旅游
计算机毕业设计木哥4 天前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计