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

Spring Security

简介

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

引入spring security组件

在 pom.xml 中加入

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

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

如果代码中不做任何设置,默认的账户是 user,默认的密码随着项目的启动,会打印在控制台中。

输入账号密码,即可进入默认的初始界面。

代码实战

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

新增代码目录

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    SPRING BOOT !!!
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    错误
</body>
</html>

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 登录,不可以进入系统,因为系统中还没有该用户。

原文地址:https://blog.51cto.com/14089205/2451419

时间: 2024-08-24 00:24:48

SpringBoot学习(二)—— springboot快速整合使用spring security组的相关文章

SpringBoot学习(二)--&gt;Spring的Java配置方式

二.Spring的Java配置方式 Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @Bean Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的: 1.@Configuration 作用于类上,相当于一个xml配置文件: 2.@Bean 作用于方法上,相当于xml配置中的<bean>: 2.示例 该示例演示了通过Java配置的方式进行配置Spring,并且实现了Spring IO

SpringBoot学习(四)--&gt;SpringBoot快速入门,开山篇

SpringBoot是伴随着Spring4.0诞生的,旨在简化开发. SpringBoot官方文档:http://spring.io/projects/spring-boot 写个示例:Hello SpringBoot 1.创建Maven工程 工程结构如下: 2.配置pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchem

springboot学习(二十二)_ 使用@Constraint注解自定义验证注解

最近项目在使用如@NotNull @Max 等配合@vaild 注解进行验证传过来的参数校验,然后通过统一异常处理,直接返回给前端,不用在业务代码中对这些参数进行校验.但是官方提供的并不能全部满足项目的需求,我经过查找发现了@Constraint这个注解. 需求 现在有的列表查询,根据查询条件进行查询,当然这些查询条件可以为null,如果存在值,就必须进行验证.这里就对长度就行验证,不为nul的时候 输入字符不能为空串,且长度必须大于等于1且小于等于10 代码实现 1.定义自定义注解 @Targ

SpringBoot学习之SpringBoot执行器

在以往的分布式开发当中,各个服务节点的监控必不可少.监控包含有很多方面,比如说:内存占用情况,节点是否健康等.在spring-boot会给我们提供相关资源监控叫做spring-boot-actuator, 通过执行器可以帮我管理和监控生产环境下的应用服务. 一.添加SpringBoot执行器的依赖 添加gradle配置依赖: dependencies { compile('org.springframework.boot:spring-boot-starter-actuator') } 二.关于

Castle ActiveRecord框架学习(二):快速搭建简单博客网站

一.数据库 1.数据表 Category:类别标签表(字段Type=1为类别,Type=2为标签) Category_Post:类别标签与文章中间表 Post:文章表 Comment:评论表 2.数据库关系图 3.简单说明 Category和Post表为多对多关系 Post和Comment表 为一对多关系 二.实体类 1.Category类: // 指定数据表,Lazy为延迟加载 [ActiveRecord("Category",Lazy=true)] public class Cat

Thymeleaf整合到Spring Security,标签sec不起作用

将 pom 文件中的 thymeleaf-extras-springsecurity4 依赖改成  thymeleaf-extras-springsecurity5 <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE<

springboot集成spring security实现restful风格的登录认证 附代码

一.文章简介 本文简要介绍了spring security的基本原理和实现,并基于springboot整合了spring security实现了基于数据库管理的用户的登录和登出,登录过程实现了验证码的校验功能. 完整代码地址:https://github.com/Dreamshf/spring-security.git 二.spring security框架简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.主要包括:用户认证

spring security之web应用安全

一.什么是web应用安全,为了安全我们要做哪些事情? 保护web资源不受侵害(资源:用户信息.用户财产.web数据信息等)对访问者的认证.授权,指定的用户才可以访问资源访问者的信息及操作得到保护(xss csrf sql注入等) 开发中我们需要注意的项:1. [高危]网络关键数据传输加密1. [高危]站点使用https方式部署2. [高危]文件传输时,过滤与业务无关的文件类型3. [高危]接口开发,应预防泄露敏感数据4. [高危]预防url中带url跳转参数5. [中危]预防CSRF攻击6. [

SpringBoot学习(七)—— springboot快速整合Redis

目录 Redis缓存 简介 引入redis缓存 代码实战 Redis缓存 @ 简介 redis是一个高性能的key-value数据库 优势 性能强,适合高度的读写操作(读的速度是110000次/s,写的速度是81000次/s ). 支持较为丰富的数据类型(如二进制的Strings, Lists, Hashes, Sets ,Ordered Sets) 一定的事物能力(要么执行成功要么完全不执行). 劣势 内存数据库访问快,但也消耗硬件内存资源 注:redis的单线程仅仅是说在网络请求这一模块上用