Spring Boot 是一个开箱即用的框架,方便开发者快速构建基于 Spring 的应用程序。而 Spring Security 则是 Spring 提供的安全框架,主要用于身份认证和权限控制。在这篇文章中,我们将讨论如何在 Spring Boot 中配置 Spring Security。

1. 添加依赖

首先,我们需要在 pom.xml 中添加 Spring Security 的依赖。如果你是使用 Gradle,可以在 build.gradle 中添加相应的依赖。

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

2. Spring Security 默认配置

当我们添加了 Spring Security 依赖后,Spring Boot 会自动提供一些基本的安全配置。默认情况下,Spring Security 会为你的应用程序提供基本的 HTTP 认证,并为你生成一个随机的用户和密码,打印在控制台上。

在这种情况下,你只需启动应用程序,然后访问任何受保护的 URL 即可。浏览器会提示你输入用户名和密码,默认用户名为 user,密码为随机生成的字符串。

3. 自定义 Spring Security 配置

如果需要自定义安全配置,我们可以创建一个配置类,继承 WebSecurityConfigurerAdapter 并重写相关的方法:

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置内存中的用户
        auth.inMemoryAuthentication()
            .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
            .and()
            .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN") // 只有 ADMIN 角色可以访问 /admin/**
                .antMatchers("/user/**").hasRole("USER")   // USER 角色可以访问 /user/**
                .anyRequest().authenticated() // 其他请求需要认证
            .and()
            .formLogin() // 开启表单登录
                .loginPage("/login") // 自定义登录页面
                .permitAll() // 允许所有用户访问登录页面
            .and()
            .logout() // 开启注销功能
                .permitAll();
    }

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

4. 自定义登录页面

接下来,我们可以创建一个自定义的登录页面,这样可以提升用户体验。创建一个 HTML 文件,比如 login.html,放在 src/main/resources/templates 目录下,内容如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登录</title>
</head>
<body>
    <h2>登录页面</h2>
    <form th:action="@{/login}" method="post">
        <div>
            <label>用户名:</label>
            <input type="text" name="username" />
        </div>
        <div>
            <label>密码:</label>
            <input type="password" name="password" />
        </div>
        <button type="submit">登录</button>
    </form>
</body>
</html>

5. 创建控制器

最后,我们需要创建一个控制器来处理用户请求。如下所示:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home() {
        return "home"; // 返回主页
    }

    @GetMapping("/login")
    public String login() {
        return "login"; // 返回登录页面
    }

    @GetMapping("/user")
    public String user() {
        return "user"; // 返回用户页面
    }

    @GetMapping("/admin")
    public String admin() {
        return "admin"; // 返回管理员页面
    }
}

6. 总结

通过上面的配置,我们成功在 Spring Boot 中集成了 Spring Security,创建了一套简单的身份认证和权限控制方案。我们定义了用户与角色,配置了 URL 访问权限,并实现了自定义的登录页面。Spring Security 提供了强大的功能,你可以根据应用需求进行进一步的配置和扩展。希望这篇文章能帮助你更好地理解 Spring Security 的配置。

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部