后端 - Spring Security 配置
package com.movie.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用内存中的用户进行演示
auth.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN")
.and()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER");
// 其他配置...
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用 CSRF 保护(实际项目中需要谨慎处理)
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // 只有管理员可以访问 /admin/**
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN") // 用户和管理员都可以访问 /user/**
.antMatchers("/", "/login", "/register").permitAll() // 允许所有人访问登录和注册页面
.anyRequest().authenticated() // 其他所有请求都需要认证
.and()
.formLogin() // 表单登录配置
.loginPage("/login") // 自定义登录页面
.permitAll() // 允许所有人访问登录页面
.and()
.logout() // 注销配置
.permitAll(); // 允许所有人发起注销请求
}
}
前端 - 登录页面
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h2 class="mt-5">Login</h2>
<form action="/login" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
后端 - 登录逻辑
// ... 其他代码保持不变 ...
@PostMapping("/login")
@ApiOperation("管理员登陆")
public ResponseEntity<?> login(@RequestBody LoginDto loginDto, HttpServletResponse response) throws Exception {
HashMap<String, String> map = new HashMap<>();
String token = adminService.login(loginDto);
if (token != null) {
map.put("token", token);
response.addHeader("Authorization", "Bearer " + token);
return ResponseEntity.ok(map);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login Failed");
}
}