使用shiro和jwt写出登录功能
时间: 2023-03-23 11:01:37 浏览: 85
可以的,使用Shiro和JWT实现登录功能的步骤如下:
1. 引入Shiro和JWT的依赖包,可以在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.1</version>
</dependency>
```
2. 在Shiro的配置文件中配置Realm和SecurityManager,以及相应的过滤器链:
```
<!-- 配置Realm -->
<bean id="myRealm" class="com.example.MyRealm">
</bean>
<!-- 配置SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
</bean>
<!-- 配置过滤器链 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="filterChainDefinitions">
<value>
/login = anon
/logout = anon
/** = jwt
</value>
</property>
</bean>
```
其中,MyRealm是自定义的Realm,jwt是自定义的过滤器,将在下面进行实现。
3. 实现自定义的Realm,用于从数据库或其他数据源中获取用户信息和角色权限等:
```
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 授权操作
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 获取当前用户的信息
User user = (User) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 给用户添加角色和权限
authorizationInfo.addRole(user.getRole());
authorizationInfo.addStringPermission(user.getPermission());
return authorizationInfo;
}
/**
* 认证操作
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 获取用户名和密码
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
// 根据用户名从数据库中获取用户信息
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
// 认证成功,返回AuthenticationInfo对象
return new SimpleAuthenticationInfo(user, password, getName());
}
}
```
其中,UserService是自定义的用户服务类,可以根据具体业务需求进行实现。
4. 实现自定义的JWT过滤器,用于生成和验证JWT令牌:
```
public class JWTFilter extends AuthenticatingFilter {
@Autowired
private UserService userService;
/**
* 生成JWT令牌
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest