首页 > Java > java教程 > 正文

春季启动中的基本身份验证

DDD
发布: 2025-02-11 11:22:01
原创
253人浏览过

spring security简明身份验证指南:基于http basic的认证

Spring Security负责Spring应用程序的身份验证和授权。本文将演示使用最基本的HTTP Basic身份验证方法来保护Spring Boot API。

首先,创建一个简单的Spring Boot应用程序,仅包含Spring Web和Spring Security依赖。 我们将添加一个简单的GET请求:

package com.example.spring_basic;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @GetMapping("/hello")
    public String hello(){
       return "Hello World!";
    }
}
登录后复制

运行应用程序后,Spring Security会自动启用默认配置,但此时安全性并未真正生效。我们可以通过工具(如IntelliJ HTTP客户端)发送请求进行测试,你会发现请求可以成功访问 /hello 接口。

春季启动中的基本身份验证

为了增强安全性,我们需要添加自定义的Spring Security配置:

package com.example.spring_basic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.httpBasic(withDefaults());
        http.authorizeHttpRequests(httpSecurity -> {
            httpSecurity.requestMatchers("/users").permitAll();
            httpSecurity.anyRequest().authenticated();
        });
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("password"))
                .roles("user")
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("password"))
                .roles("user", "admin")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
}
登录后复制

此配置使用httpBasic(withDefaults())启用HTTP Basic身份验证,并定义了两个用户:"user"和"admin",密码均为"password"(已使用BCryptPasswordEncoder加密)。 /users 路径允许匿名访问,其他所有请求都需要身份验证。

现在,我们需要使用用户名和密码进行身份验证才能访问 /hello 接口:

GET http://localhost:8080/hello
Authorization: Basic dXNlcjpwYXNzd29yZA==  // "user:password" 的Base64编码
登录后复制

春季启动中的基本身份验证

工作原理:

当客户端发送请求时,BasicAuthenticationFilter拦截请求,提取Authorization header中的凭据。 AuthenticationManager调用DaoAuthenticationProvider,使用InMemoryUserDetailsManager验证用户名和密码。 如果验证成功,则将身份验证信息添加到SecurityContext,允许访问受保护的资源。

项目源码:此处替换为实际源码链接或说明

通过以上步骤,我们成功地使用HTTP Basic身份验证保护了Spring Boot应用程序。 记住,在生产环境中,应使用更安全的身份验证方法,例如OAuth 2.0或JWT。

以上就是春季启动中的基本身份验证的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号