实现基于角色的权限管理

以下示例使用 Spring Security 实现基于角色的权限控制,包含用户认证和授权逻辑:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("admin")
            .password("{noop}admin123")
            .roles("ADMIN")
            .and()
            .withUser("user")
            .password("{noop}user123")
            .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
            .antMatchers("/", "/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/dashboard")
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout");
    }
}

使用JPA实现从数据库加载用户和权限:

@Entity
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Role> roles;

    // 实现UserDetails接口方法
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
            .map(role -> new SimpleGrantedAuthority(role.getName()))
            .collect(Collectors.toList());
    }
}

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return user;
    }
}

方法级权限控制

在服务层使用方法级安全注解:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long userId) {
    // 管理员专属操作
}

@PreAuthorize("hasAuthority('WRITE_PRIVILEGE')")
public void updateContent(Content content) {
    // 需要写权限的操作
}

@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long docId) {
    // 只能访问自己的文档
}

自定义权限表达式

创建自定义权限校验逻辑:

@Component("perm")
public class PermissionEvaluator {
    public boolean check(Authentication auth, String permission) {
        // 自定义权限校验逻辑
        return auth.getAuthorities().stream()
            .anyMatch(g -> g.getAuthority().equals(permission));
    }
}

// 在控制器中使用
@PreAuthorize("@perm.check(authentication, 'SPECIAL_PERM')")
public void specialOperation() {
    // 需要SPECIAL_PERM权限的操作
}

CSRF防护配置

配置CSRF保护并排除API端点:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
        .ignoringAntMatchers("/api/**")
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

以上代码示例展示了Spring Security的核心权限管理功能实现,可根据实际需求进行组合和扩展。生产环境应使用密码加密、HTTPS等安全措施增强系统安全性。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐