首页 > 其他分享 >Spring Boot —— Spring Security

Spring Boot —— Spring Security

时间:2024-05-22 22:40:50浏览次数:22  
标签:用户名 自定义 登录 Spring boot Boot Security

引入依赖

Spring boot 版本 2.7.6

<properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.7.6</spring-boot.version>
        <mysql.version>8.2.0</mysql.version>
        <druid.version>1.2.22</druid.version>
    </properties>
	
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
	
	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
	</dependencies>

Spring Security 开始工作了吗

引入Spring Security之后,默认会保(拦)护(截)所有请求,此时使用浏览器访问任意请求(地址)会发现跳转到一个登录页,说明 Spring Security 已经开始工作了,以 Spring Security 5.7.5 为例
image

如果我们什么都不配置,默认的用户名是user,而密码会在启动时输出到控制台Using generated security password: 8c189297-d9c5-483a-9ae2-8efb64129776

配置

自定义用户名和密码

修改配置文件,使用自定义用户名和密码

spring:
  security:
    user:
	  name: admin
	  password: 123456

使用配置类控制 Spring Security 行为

写一个SecurityConfig类,里边定义对 Spring Security 行为的控制,例如

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests((auth)->{
            try {
                auth.anyRequest().authenticated()
                        .and()
						// 使用表单登录
                        .formLogin()
                        // 登录成功跳转地址,第二个参数控制是否忽略来源页面始终跳转所设置的地址
                        .defaultSuccessUrl("/authentication")
                        .and()
                        .csrf().disable();
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        });

        return http.build();
    }
}

这是一个非常基础的配置类,启用表单登录并且使用Spring Security默认登录页面(因为没有设置自定义登录页),登录成功默认跳转/authentication。很多书上对此部分的介绍是使SecurityConfig继承WebSecurityConfigurerAdapter,并通过重写configure(AuthenticationManagerBuilder builder)configure(HttpSecurity http)方法达到更多控制

自定义登录页面

如果使用自定义登录页面,通常页面中的用户名或密码会这样写

<input name="username" />
<input name="password" />

如果希望修改表示用户名和密码的关键字,可以通过设置HttpSecurity对应方法,同时修改input的name属性达到目的

.formLogin()
.usernameParameter("uid")
.passwordParameter("pwd")
<input name="uid" />
<input name="pwd" />

基于内存的认证

模拟内存中添加若干用户,这些用户被设置用户名、密码和角色,并在登录时起作用

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	@Override
	protected void configure(AuthenticationManagerBuilder builder) throws Exception{
		builder.inMemoryAuthentication()
			.withUser("admin").password("123456").roles("ADMIN")
			.and()
			.withUser("user").password("123456").roles("USER")
	}
}

标签:用户名,自定义,登录,Spring,boot,Boot,Security
From: https://www.cnblogs.com/cinlap/p/18207299

相关文章

  • 【SpringBoot】服务停止数据源的关闭时机
    1 前言微服务中我们会用到数据源,数据源中其实就是管理我们的数据库连接,对于数据库而言,连接数是很珍贵的资源,所以释放无用或者长时间空闲的连接显得很重要。那么对于微服务比如我们的SpringBoot当服务启动的时候会初始化数据源,那么停止的时候,是如何关闭数据源,释放连接的呢?这......
  • 在springboot项目中,打包本地的外部jar包,到运行的jar包中
    1、配置依赖<dependency><groupId>com.genesyslab</groupId><artifactId>genesyslab</artifactId><version>1.0.0</version><scope>system</scope><systemPath>${project.basedir}/src/main/re......
  • springboot开启热部署
    一、依赖在SpringBoot中启用热部署通常涉及使用SpringBootDevTools依赖和配置。以下是如何在SpringBoot项目中启用热部署的步骤:在pom.xml中添加SpringBootDevTools依赖:<dependencies><!--其他依赖--><dependency><groupId>org.springframework.b......
  • springboot中执行完某些逻辑后,才算bean加载完,applicationContext才加载完毕
    核心思想实现InitializingBean接口,重写afterPropertiesSet方法范例代码importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.stereotype.Component;@Slf4j@ComponentpublicclassDemoimplementsI......
  • spring cloud
    什么是SpringCloud?基于SpringBoot的Spring集成应用程序,它利用SpringBoot的开发便利性简化了分布式系统的开发,提供与外部系统的集成。如服务注册与发现、配置中心、负载均衡、断路器、消息总线、数据监控等;换句话说:SpringCloud提供了构建分布式系统所需的“全家桶......
  • 使用winsw 将 spring boot jar包注册称服务
    下载地址:ReleaseWinSWv2.10.3·winsw/winsw·GitHub下载winsw,使用版本WinSWv2.10.3版修改文件名  修改配置<configuration><!--安装成Windows服务后的服务名--><id>nacosConsumer</id><!--显示的服务名称--><name>nacosConsumer</name>&......
  • springboot集成logback-spring.xml日志文件
    logback-spring.xml:<!--Logbackconfiguration.Seehttp://logback.qos.ch/manual/index.html--><configurationscan="true"scanPeriod="10seconds"><springPropertyscope="context"name="logLevel"s......
  • Java核心面试知识集—Spring面试题
    Spring概述(10)什么是spring?Spring是一个轻量级Java开发框架,最早有RodJohnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题。它是一个分层的JavaSE/JavaEEfull-stack(一站式)轻量级开源框架,为开发Java应用程序提供全面的基础架构支持。Spring负责基础架构,......
  • Java核心面试知识集—SpringMVC面试题
    概述什么是SpringMVC?简单介绍下你对SpringMVC的理解?SpringMVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架,通过把模型-视图-控制器分离,将web层进行职责解耦,把复杂的web应用分成逻辑清晰的几部分,简化开发,减少出错,方便组内开发人员之间的配合。SpringMVC......
  • Java核心面试知识集—SpringBoot面试题
    概述什么是SpringBoot?SpringBoot是Spring开源组织下的子项目,是Spring组件一站式解决方案,主要是简化了使用Spring的难度,简省了繁重的配置,提供了各种启动器,开发者能快速上手。SpringBoot有哪些优点?SpringBoot主要有如下优点:容易上手,提升开发效率,为Spring开发......