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/z41 著作权归作者所有。请勿转载和采集!

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