java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Security使用

Spring Security简介、使用与最佳实践

作者:妳人話

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍Spring Security使用与最佳实践,感兴趣的朋友跟随小编一起看看吧

一、如何理解 Spring Security?—— 核心思想

        Spring Security 的核心是一个基于过滤器链(Filter Chain)的认证和授权框架。不要把它想象成一个黑盒,而是一个可以高度定制和扩展的安全卫士。

二、如何在 Java 项目中使用?—— 实战步骤

我们以一个最常见的场景为例:使用数据库存储用户信息,并实现基于角色(Role)的页面访问控制

环境准备

步骤一:定义用户和角色实体 (Entity)

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name; // e.g., "ROLE_USER", "ROLE_ADMIN"
    // Constructors, getters, setters...
}
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private Boolean enabled;
    @ManyToMany(fetch = FetchType.EAGER) // 急加载,获取用户时立刻获取角色
    @JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles = new HashSet<>();
    // Constructors, getters, setters...
}

步骤二:实现 UserDetailsService - 连接数据库和Security的桥梁

这是最关键的接口。Spring Security 会调用它的 loadUserByUsername 方法来根据用户名获取用户信息。

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository; // 你的JPA Repository
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 从数据库查询用户
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        // 2. 将数据库中的 User 对象,转换为 Spring Security 认识的 UserDetails 对象
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .disabled(!user.getEnabled())
                .authorities(getAuthorities(user.getRoles())) // 这里设置权限/角色
                .build();
    }
    // 将数据库中的 Role 集合转换为 Spring Security 认识的 GrantedAuthority 集合
    private Collection<? extends GrantedAuthority> getAuthorities(Set<Role> roles) {
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());
    }
}

步骤三:安全配置类 (Security Configuration) - 核心配置

这是你定义安全规则的地方:哪些URL需要保护?谁可以访问?登录/登出怎么处理?

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private MyUserDetailsService userDetailsService;
    // 配置密码编码器。Spring Security 强制要求密码必须加密。
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 授权配置:定义哪些请求需要什么权限
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/", "/home", "/public/**").permitAll() // 允许所有人访问
                .requestMatchers("/admin/**").hasRole("ADMIN") // 只有ADMIN角色可以访问
                .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") // USER或ADMIN角色可以访问
                .anyRequest().authenticated() // 所有其他请求都需要认证(登录)
            )
            // 表单登录配置
            .formLogin(form -> form
                .loginPage("/login") // 自定义登录页面路径
                .permitAll() // 允许所有人访问登录页面
                .defaultSuccessUrl("/dashboard") // 登录成功后的默认跳转页面
            )
            // 登出配置
            .logout(logout -> logout
                .permitAll()
                .logoutSuccessUrl("/login?logout") // 登出成功后跳转的页面
            )
            // 记住我功能
            .rememberMe(remember -> remember
                .key("uniqueAndSecret") // 用于对 token 进行哈希的密钥
                .tokenValiditySeconds(86400) // 记住我有效期为1天
            )
            // 异常处理:权限不足时
            .exceptionHandling(handling -> handling
                .accessDeniedPage("/access-denied")
            )
            // 关键:配置自定义的 UserDetailsService
            .userDetailsService(userDetailsService);
        return http.build();
    }
}

步骤四:控制器和视图 (Controller & View)

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home"; // home.html
    }
    @GetMapping("/admin/dashboard")
    public String adminDashboard() {
        return "admin-dashboard";
    }
    @GetMapping("/user/dashboard")
    public String userDashboard() {
        return "user-dashboard";
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @GetMapping("/access-denied")
    public String accessDenied() {
        return "access-denied";
    }
}

在 templates/login.html 中,你需要一个符合 Spring Security 约定的表单:

<form th:action="@{/login}" method="post">
    <input type="text" name="username" placeholder="Username"/>
    <input type="password" name="password" placeholder="Password"/>
    <input type="checkbox" name="remember-me"/> Remember Me
    <button type="submit">Login</button>
</form>

注意th:action="@{/login}"name="username"name="password" 都是默认的,不能随意更改。

步骤五:在视图和控制器中获取用户信息

// 在Controller中获取当前用户
@GetMapping("/profile")
public String profile(Model model) {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
        String username = ((UserDetails) principal).getUsername();
        model.addAttribute("username", username);
    }
    return "profile";
}
// 更优雅的方式:使用 Principal 对象直接注入
@GetMapping("/profile2")
public String profile2(Principal principal, Model model) {
    model.addAttribute("username", principal.getName());
    return "profile";
}

在 Thymeleaf 模板中,可以直接使用 Securty 表达式:

<div th:if="${#authorization.expression('isAuthenticated()')}">
    <p>Welcome, <span th:text="${#authentication.name}">User</span>!</p>
    <p>You have roles: <span th:text="${#authentication.authorities}">[]</span></p>
</div>

总结与最佳实践

@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public User getUserById(Long userId) { ... }

到此这篇关于Spring Security使用与最佳实践的文章就介绍到这了,更多相关Spring Security使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文