使用Spring加Shiro写一个登录,需要详细代码
时间: 2024-01-30 14:04:28 浏览: 24
以下是使用Spring加Shiro写一个简单的登录功能的详细代码。
1. 配置Shiro
在Spring的配置文件中,配置Shiro的相关内容:
```
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<bean id="myRealm" class="com.example.MyRealm"/>
<bean class="org.springframework.web.filter.DelegatingFilterProxy">
<property name="targetFilterLifecycle" value="true"/>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="successUrl" value="/index"/>
<property name="filterChainDefinitions">
<value>
/login = anon
/logout = logout
/** = authc
</value>
</property>
</bean>
```
在上述配置中,我们配置了Shiro的安全管理器、自定义Realm、Shiro的过滤器等。
2. 编写登录页面
在登录页面中,我们需要使用表单来提交用户名和密码。为了与Shiro进行集成,我们需要在表单中添加名为“rememberMe”的复选框,用于实现记住我功能。
```
<form method="post" action="/login">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="checkbox" name="rememberMe">记住我
<button type="submit">登录</button>
</form>
```
3. 编写自定义Realm
我们需要继承Shiro的Realm类,并实现其中的认证和授权方法。
```
public class MyRealm extends AuthorizingRealm {
/**
* 认证方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
String password = new String(upToken.getPassword());
// 根据用户名从数据库中获取用户信息
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户不存在");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("密码错误");
}
return new SimpleAuthenticationInfo(user, password, getName());
}
/**
* 授权方法
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(user.getRoles());
info.setStringPermissions(user.getPermissions());
return info;
}
}
```
在上述代码中,我们从数据库中获取用户信息,并对用户名和密码进行验证。如果验证通过,则返回一个AuthenticationInfo对象,在后续的认证流程中使用。
在授权方法中,我们从用户信息中获取用户的角色和权限等信息,用于后续的授权流程。
4. 编写登录Controller
在登录Controller中,我们需要处理用户提交的表单数据,并进行Shiro认证流程。
```
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(HttpServletRequest request) {
String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
if (exceptionClassName != null) {
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
request.setAttribute("errorMsg", "用户不存在");
} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
request.setAttribute("errorMsg", "密码错误");
} else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
request.setAttribute("errorMsg", "认证失败");
} else if (LockedAccountException.class.getName().equals(exceptionClassName)) {
request.setAttribute("errorMsg", "账号被锁定");
} else {
request.setAttribute("errorMsg", "未知错误");
}
}
return "login";
}
}
```
在上述代码中,我们判断Shiro认证过程中是否出现异常,并将异常信息存储到request中,用于在登录页面中显示错误信息。
5. 编写登录成功跳转Controller
在登录成功后,我们需要跳转到指定的页面。在Spring MVC中,我们可以使用redirect方式来实现。
```
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
```
在上述代码中,我们配置了一个/index的请求映射,用于跳转到index页面。
6. 编写注销Controller
在注销Controller中,我们需要清除Shiro中的缓存信息,并跳转到登录页面。
```
@Controller
public class LogoutController {
@RequestMapping("/logout")
public String logout() {
SecurityUtils.getSubject().logout();
return "redirect:/login";
}
}
```
在上述代码中,我们使用SecurityUtils.getSubject()来获取当前用户的Subject对象,并调用其logout()方法来清除缓存。最后,我们使用redirect方式跳转到登录页面。
以上就是使用Spring加Shiro写一个简单的登录功能的详细代码。