shiro+springboot+jwt项目
时间: 2023-08-28 13:07:49 浏览: 148
Shiro是一个Java安全框架,可以提供身份验证、授权、加密和会话管理等功能,Spring Boot是一个快速开发框架,可以帮助开发人员更快地构建和部署应用程序,JWT(JSON Web Token)是一种轻量级的身份验证和授权机制。将这三个框架结合起来,可以构建一个安全的Web应用程序。
以下是一个简单的Shiro+Spring Boot+JWT项目的实现步骤:
1.创建一个Spring Boot项目,并添加Shiro和JWT依赖项:
```
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
```
2.创建一个Shiro配置类,配置Shiro的安全策略和过滤器链:
```
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/**", "jwt");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public DefaultWebSecurityManager securityManager(Realm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
return securityManager;
}
@Bean
public Realm realm() {
return new UserRealm();
}
@Bean
public JwtFilter jwtFilter() {
return new JwtFilter();
}
}
```
3.创建一个自定义Realm类,实现Shiro的认证和授权逻辑:
```
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principals.getPrimaryPrincipal();
authorizationInfo.addRole(user.getRole());
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException();
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
}
```
4.创建一个JwtFilter类,实现JWT的认证逻辑:
```
public class JwtFilter extends AuthenticatingFilter {
@Autowired
private UserService userService;
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader("Authorization");
if (StringUtils.isEmpty(token)) {
throw new UnauthorizedException();
}
JwtToken jwtToken = new JwtToken(token);
try {
getSubject(request, response).login(jwtToken);
} catch (AuthenticationException e) {
throw new UnauthorizedException();
}
return true;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
return false;
}
}
```
5.创建一个JwtToken类,实现JWT的Token逻辑:
```
public class JwtToken implements AuthenticationToken {
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return JwtUtils.getSubject(token);
}
@Override
public Object getCredentials() {
return token;
}
}
```
6.创建一个UserController类,实现用户登录和获取用户信息的逻辑:
```
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Result login(@RequestBody User user) {
String token = userService.login(user);
return Result.success(token);
}
@GetMapping("/user")
public Result getUserInfo() {
User user = (User) SecurityUtils.getSubject().getPrincipal();
return Result.success(user);
}
}
```
7.创建一个UserService类,实现用户登录和生成JWT Token的逻辑:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}
public String login(User user) {
User realUser = findByUsername(user.getUsername());
if (realUser == null || !realUser.getPassword().equals(user.getPassword())) {
throw new UnauthorizedException();
}
return JwtUtils.generateToken(realUser.getId(), realUser.getUsername(), realUser.getRole());
}
}
```
8.创建一个JwtUtils类,实现JWT的Token生成和解析逻辑:
```
public class JwtUtils {
private static final String SECRET = "secret";
private static final long EXPIRATION_TIME = 86400000; // 24 hours
public static String generateToken(String id, String username, String role) {
Date now = new Date();
Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setId(id)
.setSubject(username)
.claim("role", role)
.setIssuedAt(now)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
public static String getSubject(String token) {
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
}
```
这样,就可以使用Shiro+Spring Boot+JWT构建一个安全的Web应用程序了。
阅读全文