下面来详细讲解如何实现Spring Boot整合Shiro和JWT的示例代码。
简介
Shiro是一个强大的安全框架,提供了多种安全特性,例如:认证、授权、加密等等。JWT是一种轻量级的认证机制,它可以使用JSON格式存储用户信息,并且可以在客户端和服务端之间传递。
本文将介绍如何通过Spring Boot实现Shiro整合JWT的示例代码。
示例1:环境搭建
首先,我们需要搭建Spring Boot的环境,具体步骤如下:
-
首先,需要安装Java环境,可参考官网文档下载并安装。
-
下载并安装Maven,可根据官网文档进行安装。
-
创建Spring Boot项目,可使用Spring Initializr进行创建。
-
在pom.xml文件中添加Shiro和JWT的依赖项,具体依赖项可参考如下代码块:
```xml
```
- 配置application.yml文件,具体配置可参考如下代码块:
```yml
# 数据库配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
# JWT配置
jwt:
secret: 123456
expireTime: 1800
# Shiro配置
shiro:
filterChainDefinitions: /login = anon\n/** = authc
loginUrl: /login
```
- 在WebMvcConfigurer中配置ShiroFilterFactoryBean,具体代码可参考如下代码块:
```java
@Configuration
public class ShiroConfig {
@Autowired
private Environment env;
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl(env.getProperty("shiro.loginUrl"));
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.putAll(parseFilterChainDefinitions(env.getProperty("shiro.filterChainDefinitions")));
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(Realm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
return securityManager;
}
@Bean
public Realm realm() {
JwtRealm realm = new JwtRealm();
realm.setCredentialsMatcher(new JwtMatcher());
return realm;
}
private Map<String, String> parseFilterChainDefinitions(String definitions) {
Map<String, String> chains = new HashMap<>();
if (StringUtils.isBlank(definitions)) {
return chains;
}
String[] definitionArray = definitions.split("\\n");
for (String definition : definitionArray) {
String[] tmp = definition.split("=");
if (tmp.length == 2) {
chains.put(tmp[0].trim(), tmp[1].trim());
}
}
return chains;
}
}
```
- 接下来就可以开始编写业务逻辑代码了。
示例2:JWT认证
首先,我们来看一下如何使用JWT实现认证。
- 首先,在Shiro的Realm中实现认证逻辑,具体代码可参考如下:
```java
public class JwtRealm extends AuthorizingRealm {
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
JwtToken jwtToken = (JwtToken) token;
Claims claims = jwtToken.getClaims();
Date expireDate = claims.getExpiration();
if (expireDate.before(new Date())) {
throw new AuthenticationException("Token expired");
}
String username = claims.getSubject();
return new SimpleAuthenticationInfo(username, token.getCredentials(), getName());
}
}
```
- 接下来,编写JWT工具类,具体代码可参考如下:
```java
public class JwtUtil {
private static final String secret = "123456";
public static String createToken(String subject, Date expireTime) {
SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
Date nowDate = new Date();
byte[] secretBytes = DatatypeConverter.parseBase64Binary(secret);
JwtBuilder builder = Jwts.builder().setId(UUID.randomUUID().toString())
.setIssuedAt(nowDate)
.setSubject(subject)
.setExpiration(expireTime)
.signWith(algorithm, secretBytes);
return builder.compact();
}
public static Claims parseToken(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(secret)).parseClaimsJws(token).getBody();
return claims;
} catch (JwtException e) {
return null;
}
}
}
```
- 最后,在Controller中编写登录接口,具体代码可参考如下:
```java
@RestController
public class AuthController {
@Value("${jwt.expireTime}")
private Long expireTime;
@PostMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
String jwtToken = JwtUtil.createToken(username, new Date(System.currentTimeMillis() + expireTime * 1000));
return jwtToken;
} catch (AuthenticationException e) {
return "login error";
}
}
}
```
通过以上步骤,就可以实现使用JWT进行认证了。
总结
本文通过示例介绍了如何通过Spring Boot实现Shiro整合JWT的示例代码,其中包括环境搭建、JWT认证等步骤,希望对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Springboot实现Shiro整合JWT的示例代码 - Python技术站