【SpringBoot】Spring Security(1):初体验

如果饿了就吃,困了就睡,渴了就喝,人生就太无趣了
源码地址:https://github.com/keer123456789/springbootstudy/tree/master/security_demo_1


1.Spring Security 简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

以上解释来源于百度百科。可以一句话来概括,SpringSecurity 是一个安全框架。
作用大致分为以下几个方面:

  • 身份认证(你是谁?)
  • 权限校验(你能做什么?允许操作的范围)
  • 攻击防护(防止伪造身份)

2.添加依赖

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

3.添加hello_world 接口

@RestController
@RequestMapping("/security")
public class Controller {
    protected Logger logger= LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "hello",method = RequestMethod.GET)
    public String hello() {
        return "hello_world";
    }
}

4.直接运行

完成上述操作后,运行SpringBoot项目,浏览器访问http://127.0.0.1/security/hello
预期结果是返回字符串:hello_world
但结果是:

在这里插入图片描述

可以看到浏览器的地址自动跳转到http://127.0.0.1:8080/login,说明此时Spring Security已经起作用了,因为Spring Security提供了一个简单的登录界面。
用户名默认为user,密码则需要看springboot启动时的日志:

在这里插入图片描述

冒号后面的就是密码,粘贴复制即可。

输入完用户名密码之后,结果如:此时浏览器的地址就是当初的地址了。

在这里插入图片描述

5.配置添加用户信息

如果不想使用默认用户登录信息,则可以在application.properties文件添加配置

spring.security.user.name=admin
spring.security.user.password=admin

重新启动项目,输入自定义的用户名密码即可登录

6.关闭 Security 功能

在开发其他功能时调试时,如果总是需要登录,则过于麻烦,此时可以在启动类上添加注解来关闭Spring Security功能。再去访问http://127.0.0.1/security/hello,直接返回hello_world

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SecurityDemo1Application {

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

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章