SpringBoot学习(二)—— springboot快速整合spring security组件
admin
2023-02-20 19:20:03
0

Spring Security

简介

spring security的核心功能为认证(Authentication),授权(Authorization),即认证用户是否能访问该系统,和授权用户可以在系统中进行哪些操作。

引入spring security组件

在 pom.xml 中加入


    org.springframework.boot
    spring-boot-starter-security


    org.springframework.security
    spring-security-test
    test

验证组件是否起到作用,现在不更改框架内的任何内容,启动项目,浏览器中依旧输入 http://localhost:8080 ,可看到如下界面,之前可以直接进入spring boot的初始界面,现在已经看不见了,spring security 导入后默认已经开启了验证,必须先登录验证通过后才能访问。

SpringBoot学习(二)—— springboot快速整合spring security组件

如果代码中不做任何设置,默认的账户是 user,默认的密码随着项目的启动,会打印在控制台中。
SpringBoot学习(二)—— springboot快速整合spring security组件

输入账号密码,即可进入默认的初始界面。
SpringBoot学习(二)—— springboot快速整合spring security组件

代码实战

为了最快最简单最直接的认识这个组件,直接把用户密码写入内存中,项目启动即存在,避免还有建表,实体类,数据库操作等与之无关的内容。命名使用最为简单粗暴的方式,排除一切干扰,用最少的精力掌握该组件的使用。

新增代码目录
SpringBoot学习(二)—— springboot快速整合spring security组件

index.html




    
    Title


    SPRING BOOT !!!

error.html




    
    Title


    错误

UserController

package com.example.controller;

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

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("/addUser")
    @ResponseBody
    String addUser() {
        return "这是添加用户!!!";
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    String deleteUser() {
        return "这是删除用户!!!";
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    String updateUser() {
        return "这是修改用户!!!";
    }

    @RequestMapping("/findAllUsers")
    @ResponseBody
    String findAllUsers() {
        return "这是查询用户!!!";
    }

}

UserSecurityConfig

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

//注解开启 Spring Security 安全认证与授权
@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    //用户认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //内存里面放着
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                //添加用户,密码,角色
                .withUser("zs").password("123456").roles("AAA")
                //链式编程
                .and()
                .withUser("ls").password("123456").roles("BBB")
                .and()
                .withUser("ww").password("123456").roles("CCC", "primary")
                .and()
                .withUser("zl").password("123456").roles("primary");
    }

    //用户授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * permitAll():允许一切用户访问
         * hasRole():url请求允许访问的角色
         * hasAnyRole() : url请求允许访问的多个角色
         * access():允许访问的角色,permitAll、hasRole、hasAnyRole 底层都是调用 access 方法
         * access("permitAll") 等价于 permitAll()
         */
        http.authorizeRequests().antMatchers("/").permitAll(); // "/":应用首页所以用户都可以访问
        http.authorizeRequests()
                .antMatchers("/user/addUser").hasRole("AAA") // 首斜杠"/"表示应用上下文,/user/addUser 请求允许 AAA 角色访问
                .antMatchers("/user/deleteUser/**").hasAnyRole("AAA", "BBB") //"/user/deleteUser/**"允许 "AAA", "BBB" 角色访问,/**匹配任意
                .antMatchers("/user/updateUser").hasAnyRole("AAA", "BBB", "CCC")//除了这种链式编程,也可以分开写
                .antMatchers("/user/findAllUsers").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        /**
         * formLogin:指定支持基于表单的身份验证
         * 当用户没有登录、没有权限时就会自动跳转到登录页面(默认 /login)
         * 当登录失败时,默认跳转到 /error
         * 登录成功时会放行
         */
        http.formLogin();
    }

}

MyPasswordEncoder

package com.example.config;

import org.springframework.security.crypto.password.PasswordEncoder;

//密码编码,Spring Security 高版本必须进行密码编码,否则报错
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

亲测效果是

以用户名 zs 登录(其角色权限为AAA),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/addUser,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 ls 登录(其角色权限为BBB),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 ww 登录(其角色权限为CCC),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 zl 登录(其角色权限为CCC),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 admin 登录,不可以进入系统,因为系统中还没有该用户。

相关内容

热门资讯

天然气炉子火太小是什么原因 天然气炉子火太小是什么原因要先排除是因为燃气灶之外的第三方原因造成的,比如说,使用的时候是用气高峰期...
煤气灶电池几号 不同型号的煤气灶可能需要不同型号的电池,常见的煤气灶电池型号有 1 号、2 号、5 号和 7 号。如...
煤气灶烧一会自动熄火两灶多会熄... 原因可能是燃起不足,供应不了两个煤气灶,可以关闭一个,若是一个也供应不上就需要补充煤气了;原因可能是...
燃气灶成黄火是什么原因 燃气灶成黄火的原因有很多,主要是以下几个方面:1. 气体供应不足:使用燃气灶时,如果气体供应不足,即...
燃气灶风门调到最大还是黄火怎么... 原因是燃气质量不稳定,燃气灶一次性空气量供给不足,导致燃烧不良生成黄焰火,还有可能是因为燃气灶的风门...
以青春之我 创青春中国 湖北武汉市,光谷实验室研究员张静宇聚力飞秒激光前沿赛道,突破技术壁垒,提升单张玻璃光盘的理论容量; ...
追觅科技全球发布会周收官 集中... 美国时间4月27日至30日,以“DREAME NEXT”为主题的追觅科技全球发布会周在硅谷收官。 四...
后退的阶梯:我在互联网公司的1... 如果说,张小满的前一本书《我的母亲做保洁》提供给公众一个刻下罕见的“劳动者视角”,那么此番《大厂小民...
原创 资... 也许AI故事的结局,不是赛博朋克的颠覆神话,而是无数个“广告收入从1块变成1块1”的枯燥细节。 作者...