Java安全最佳实践
Java安全最佳实践
概述
安全是应用程序的重要组成部分。本教程介绍Java应用的安全最佳实践。
1. 认证与授权
import org.springframework.context.annotation.*;
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(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.oauth2Login()
.and()
.jwt();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
// JWT认证
@Component
public class JwtTokenProvider {
private String jwtSecret = "secret";
private long jwtExpiration = 86400000;
public String generateToken(Long userId, String username) {
return Jwts.builder()
.setSubject(Long.toString(userId))
.claim("username", username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}
}
2. 数据保护
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
@Component
public class DataProtection {
private final TextEncryptor encryptor;
public DataProtection() {
this.encryptor = Encryptors.text("password", "salt");
}
public String encrypt(String data) {
return encryptor.encrypt(data);
}
public String decrypt(String encryptedData) {
return encryptor.decrypt(encryptedData);
}
}
// SQL注入防护
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findByUsername(String username) {
String sql = "SELECT * FROM users WHERE username = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{username}, User.class);
}
}
// XSS防护
@Component
public class XssFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
chain.doFilter(new XssRequestWrapper((HttpServletRequest) request), response);
}
}
3. 实际应用示例
安全配置
# application.yml
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
jwt:
secret: ${JWT_SECRET}
expiration: 86400000
API安全
@RestController
@RequestMapping("/api/secure")
public class SecureController {
@GetMapping("/data")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<String> getSecureData() {
return ResponseEntity.ok("安全数据");
}
@PostMapping("/data")
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<Void> createSecureData(@RequestBody Data data) {
// 创建数据
return ResponseEntity.ok().build();
}
}
4. 最佳实践
- 使用HTTPS:确保通信安全
- 输入验证:验证所有用户输入
- 密码加密:使用BCrypt等强加密算法
- SQL注入防护:使用PreparedStatement
- XSS防护:转义用户输入
- CSRF防护:使用CSRF令牌
- 安全配置:正确配置安全框架
总结
安全是应用程序的重要组成部分。掌握Java应用的安全最佳实践,可以构建安全可靠的应用系统。