spring-security入门1---springboot项目搭建+简单修改Spring-Security的默认行为


项目源码地址 https://github.com/nieandsun/security

1. 项目搭建关键步骤(开发工具为idea,项目为springboot项目)

①新建项目时要选上如下两个依赖

在这里插入图片描述

②项目创建完成后的pom.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nrsc</groupId>
    <artifactId>security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>

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

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

</project>

2. Spring-Security默认行为演示

①创建一个简单的Controller,项目目录结构如下

在这里插入图片描述

②启动项目,访问localhost:8080/hello结果如下

在这里插入图片描述

③上面的Username是固定的为user,Password可在项目启动日志里找到

在这里插入图片描述

④输入用户名和密码后就可以访问到期望访问的资源了,访问内容如下

在这里插入图片描述

3.简单修改Spring-Security的默认行为

  • 创建一个类继承WebSecurityConfigurerAdapter类,springboot在启动时会去看是否有WebSecurityConfigurerAdapter类的继承类,如果有的话,将按照该类中指定的方式来确定spring-security的作用行为

①创建SecurityConfig类继承WebSecurityConfigurerAdapter,这里仅仅修改spring-security的认证方式,代码及相关解释如下

在这里插入图片描述

②重新启动项目,访问localhost:8080/hello结果如下

可以看到项目的登陆方式已经发生了改变
在这里插入图片描述

说明:继承了WebSecurityConfigurerAdapter类的SecurityConfig类还可以进行其他复杂的配置,如自定义认证页面,指定哪些页面可以不经过认证等…

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值