springboot登录验证jwt
时间: 2023-12-28 16:26:13 浏览: 106
在Spring Boot中实现JWT登录验证可以结合Shiro和Redis来实现。下面是一个简单的示例代码:
1. 首先,需要添加相关依赖:
```xml
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 创建一个JWT工具类,用于生成和解析JWT:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(String username) {
Date now = new Date();
Date expireDate = new Date(now.getTime() + expiration * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
```
3. 创建一个自定义的Realm类,用于处理登录验证和权限控制:
```java
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
public class JwtRealm extends AuthenticatingRealm {
@Autowired
private JwtUtils jwtUtils;
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
JwtToken jwtToken = (JwtToken) authenticationToken;
String token = jwtToken.getToken();
if (!jwtUtils.validateToken(token)) {
throw new IncorrectCredentialsException("Token无效");
}
String username = jwtUtils.getUsernameFromToken(token);
// TODO: 根据用户名查询用户信息
return new SimpleAuthenticationInfo(username, token, getName());
}
}
```
4. 创建一个自定义的Filter类,用于处理JWT的验证和授权:
```java
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JwtFilter extends BasicHttpAuthenticationFilter {
@Autowired
private JwtUtils jwtUtils;
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7);
}
if (jwtUtils.validateToken(token)) {
return true;
}
throw new UnauthorizedException("Token无效");
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
}
```
5. 在Spring Boot的配置文件中配置相关参数:
```properties
# JWT配置
jwt.secret=your_secret_key
jwt.expiration=3600
```
6. 在Spring Boot的配置类中配置Shiro和Redis:
```java
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.apache.shiro.session.mgt.eis.SimpleSessionIdGenerator;
import org.apache.shiro.session.mgt.eis.SessionIdCookie;
import org.apache.shiro.session.mgt.eis.SessionIdCookieEnabled;
import org.apache.shiro.session.mgt.eis.SessionIdCookieSessionFactory;
import org.apache.shiro.session.mgt.eis.SessionIdUrlRewritingEnabled;
import org.apache.shiro.session.mgt.eis.SessionManagerEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationScheduler;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerFactory;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactory;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManager;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManagerEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled;
import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled
阅读全文