创建Spring Security项目并实现基于JWT的身份验证和授权
在这个项目中,我们将创建一个新的Spring Boot和Spring Security项目,并实现基于JWT的认证和授权。我们将创建一个端点,接受用户的ID和密码进行认证,并返回JWT。然后,我们将验证请求中Authorization头中的JWT,并授权具有相应权限的请求。
接下来,我将开始创建一个新的Spring Boot项目,可以通过访问start.spring.io进行。我的包名是com.javabrains,并将这个项目命名为Spring Security JWT Demo。需要添加的依赖项包括Web和Security,这两个是我们现在要添加的,稍后我们将添加一些更多的依赖项。
项目在IntelliJ中打开后,我要做的第一件事是创建一个端点,我将其称为HelloResource,这是一个控制器类,并且包含一个简单的方法。这个方法的端点为/hello,返回字符串"Hello World"。这本身没有什么特别之处,唯一的原因是我需要一个可以放在认证墙后面的API,这样只有经过认证的用户才能访问这个API。由于我们在类中添加了Spring Security,默认情况下,Spring Security会创建一个用户,并且这个/hello端点将被放在认证墙后面,只有经过认证的用户才能访问。
创建HelloController,用于创建 /hello 端点:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}
接下来,我们希望增加一些灵活性,并且希望自定义一个用户。因此,我们将使用UserDetailsService方法来覆盖默认的用户行为,并创建一个MyUserDetailsService的实现类,返回一个静态用户。我们将把这个MyUserDetailsService配置到Spring Security框架中,使其使用我们自定义的MyUserDetailsService。
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 这里可以替换为从数据库中加载用户信息的逻辑
if (username.equals("user")) {
return User.withUsername("user")
.password("password")
.roles("USER")
.build();
} else {
throw new UsernameNotFoundException("User not found with username: " + username);
}
}
}
接下来,我将创建一个安全配置类,命名为SecurityConfigurer,继承WebSecurityConfigurerAdapter。然后,我们可以使用configure方法来设置AuthenticationManagerBuilder的值,我将使用自定义的UserDetailsService。我们需要创建一个MyUserDetailsService类,实现UserDetailsService接口,并在其中定义一个方法,通过用户名加载用户。这个类将被标注为@Service,使其成为一个Spring服务。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exc