SpringSecurity(安全)

导读:本篇文章讲解 SpringSecurity(安全),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

SpringSecurity(安全)

官网:
https://docs.spring.io/spring-security/reference/index.html
SpringSecurity(安全)

一、简介

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • webSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnablewebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是”“认证”和”授权”(访问控制)。

“认证”(Authentication)
“授权”(Authorization)

这个概念是通用的,而不是只在Spring Security中存在。

包结构
在这里插入图片描述
1、导入依赖

  <!--security,thymeleaf 整合-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>


        <!--security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.6.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
            <version>2.6.6</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>
    </dependencies>

2、导入资源
在这里插入图片描述
3、编写一些请求,让他们跳转

package com.baidu.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 toLogin() {
        return "views/login";
    }

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

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

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

3、创建一个Config 包,新建Security 类

package com.baidu.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 Security 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)
        http.formLogin();

    }

    //认证 ,,
    //密码编码:passwordEncoder
    @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("tiechui").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");

    }
}

注销以及权限功能;

//没有授权默认会到登录页面,需要开启的页面
//这里看源码就可以知道,loginPage的默认值是("/login"),而loginProcessingUrl的默认值是loginPage的值
http.formLogin().loginPage("/toLogin").usernameParameter("name").passwordParameter("pwd");

//开启了,注销功能;
http.csrf().disable(); //关闭csrf,登录失败,肯定存在的原因
http.logout().logoutSuccessUrl("/");

效果:Security就不会走源码默认的Login 请求,就会走我们的toLogin请求,跳转到自己写的login页面。

显示用户名和角色:

1、导入头文件

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

最终实现效果

在这里插入图片描述在这里插入图片描述

代码实现:
在这里插入图片描述
效果:不同的角色显示不同的页面

在这里插入图片描述在这里插入图片描述
代码实现:

在这里插入图片描述
记住我;

//记住我功能  Cookie
http.rememberMe();

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71838.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!