写一套SpringBoot+Security+JWT的动态授权
时间: 2023-07-04 07:21:50 浏览: 107
好的,下面是SpringBoot+Security+JWT的动态授权的实现步骤:
1. 首先,我们需要添加Spring Security和JWT的依赖。在pom.xml文件中添加如下代码:
```
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
2. 添加JWT的配置类。创建一个JwtConfig类,用于生成JWT Token和解析JWT Token。代码如下:
```
@Configuration
public class JwtConfig {
private String secret = "jwt_secret_key";
private long expire = 604800000;
@Bean
public JwtAuthTokenGenerator jwtAuthTokenGenerator() {
return new JwtAuthTokenGenerator(secret, expire);
}
@Bean
public JwtAuthTokenVerifier jwtAuthTokenVerifier() {
return new JwtAuthTokenVerifier(secret);
}
}
```
3. 添加Spring Security的配置类。创建一个SecurityConfig类,配置Spring Security的一些基本设置。代码如下:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(jwtAuthenticationProvider());
}
@Bean
public JwtAuthenticationProvider jwtAuthenticationProvider() {
return new JwtAuthenticationProvider(jwtAuthTokenVerifier());
}
}
```
4. 添加JwtAuthenticationFilter类。创建一个JwtAuthenticationFilter类,用于在每个请求中验证JWT Token。代码如下:
```
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = getToken(request);
if (token != null) {
JwtAuthToken authToken = new JwtAuthToken(token);
Authentication authentication = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getToken(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
}
```
5. 添加JwtAuthenticationProvider类。创建一个JwtAuthenticationProvider类,用于验证JWT Token是否有效。代码如下:
```
public class JwtAuthenticationProvider implements AuthenticationProvider {
private JwtAuthTokenVerifier jwtAuthTokenVerifier;
public JwtAuthenticationProvider(JwtAuthTokenVerifier jwtAuthTokenVerifier) {
this.jwtAuthTokenVerifier = jwtAuthTokenVerifier;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
JwtAuthToken authToken = (JwtAuthToken)authentication;
String token = authToken.getToken();
if (jwtAuthTokenVerifier.verify(token)) {
return new JwtAuthenticatedUser(token);
}
throw new BadCredentialsException("Invalid JWT token");
}
@Override
public boolean supports(Class<?> authentication) {
return JwtAuthToken.class.isAssignableFrom(authentication);
}
}
```
6. 添加JwtAuthToken类。创建一个JwtAuthToken类,用于包装JWT Token。代码如下:
```
public class JwtAuthToken extends AbstractAuthenticationToken {
private String token;
public JwtAuthToken(String token) {
super(null);
this.token = token;
}
@Override
public Object getCredentials() {
return token;
}
@Override
public Object getPrincipal() {
return null;
}
}
```
7. 添加JwtAuthenticatedUser类。创建一个JwtAuthenticatedUser类,用于标识已通过验证的用户。代码如下:
```
public class JwtAuthenticatedUser implements Authentication {
private String token;
public JwtAuthenticatedUser(String token) {
this.token = token;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
return null;
}
}
```
8. 最后,添加一个LoginController类,用于登录并获取JWT Token。代码如下:
```
@RestController
public class LoginController {
@Autowired
private JwtAuthTokenGenerator jwtAuthTokenGenerator;
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody User user) {
if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
String token = jwtAuthTokenGenerator.generateToken(user.getUsername());
return ResponseEntity.ok(token);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
```
这就是SpringBoot+Security+JWT的动态授权的实现步骤,希望对你有所帮助!
阅读全文