Spring Security 是 Spring 框架中的一个安全框架,它提供了一系列的安全控制功能,包括身份认证、授权、会话管理等。下面是一个基本的 Spring Security 示例。

  1. 添加 Spring Security 依赖

在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.4.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.4.2</version>
</dependency>
  1. 配置 Spring Security

创建一个 SecurityConfig 类,继承 WebSecurityConfigurerAdapter,并添加以下内容:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser('user').password('{noop}password').roles('USER');
    }
}

这个配置中定义了一个 HTTP 安全配置,其中:

  • authorizeRequests() 定义了哪些请求需要被保护。
  • formLogin() 定义了使用表单登录来认证用户。
  • configureGlobal() 定义了使用内存认证,用户名为 user,密码为 password。
  1. 创建登录页面

在 src/main/resources/templates 目录下创建一个 login.html 页面,用于用户登录。

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>Login Page</title>
</head>
<body>
    <h1>Login Page</h1>

    <form action='/login' method='post'>
        <label for='username'>Username:</label>
        <input type='text' id='username' name='username' required>

        <br>

        <label for='password'>Password:</label>
        <input type='password' id='password' name='password' required>

        <br>

        <input type='submit' value='Login'>
    </form>
</body>
</html>
  1. 创建首页

在 src/main/resources/templates 目录下创建一个 home.html 页面,用于用户登录后的首页。

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>Home Page</title>
</head>
<body>
    <h1>Home Page</h1>

    <p>Welcome, you are logged in!</p>

    <form action='/logout' method='post'>
        <input type='submit' value='Logout'>
    </form>
</body>
</html>
  1. 运行应用程序

启动应用程序,并在浏览器中访问 http://localhost:8080/home,应该会跳转到登录页面。输入用户名和密码后,应该会跳转到首页。

这个示例演示了如何使用 Spring Security 来保护 Web 应用程序,并提供了一个基本的登录页面和首页。实际应用中,可以使用数据库或 LDAP 等来进行认证和授权。

Spring Security 入门示例:配置安全认证与授权

原文地址: http://www.cveoy.top/t/topic/lOa2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录