代码音符

spring security 3.3.0 结合 spring reactive 配置

创建时间: 6-21 15:39

浏览: 22

发现很多教程旧版本和新版本部分配置发生了改变,故记录一下配置过程。

pom.xml:

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

创建 SecurityConfig

package com.test.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
                .csrf(ServerHttpSecurity.CsrfSpec::disable)
                .authorizeExchange(authorize -> authorize
                        .pathMatchers("/login").permitAll() // 允许所有人访问登录接口
                        .anyExchange().authenticated() // 其他所有请求都需要认证
                )
                .formLogin(ServerHttpSecurity.FormLoginSpec::disable) // 禁用表单登录,因为我们用的是REST API
                .httpBasic(Customizer.withDefaults()); // 启用HTTP Basic认证,适用于API,也可以选择JWT等其他认证方式
        return http.build();
    }

}

测试 Controller:

package com.test.controller;

import com.createdpro.ao.LoginAO;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class LoginController {

    @PostMapping("/login")
    public Mono<String> login(@RequestBody @Valid Mono<LoginAO> ao) {
        return ao
                .filter(loginAO -> loginAO.getAccount().equals("user") && loginAO.getPassword().equals("123456"))
                .map(loginAO -> "用户" + loginAO.getAccount() + "登录成功!")
                .defaultIfEmpty("账号或密码错误");
    }

}

创建时间: 6-21 15:39

浏览: 22

*本文遵循 CC BY-NC-SA 许可协议。转载请注明出处!