Apache Shiro:https://shiro.apache.org/
依赖
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.1</version>
</dependency>
ShiroConfig.java
@Configuration
public class ShiroConfig {// 创建 Realm 对象(携带权限信息)@Beanpublic UserRealm userRealm(){return new UserRealm();}// 安全管理器@Beanpublic DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 设置要管理的用户securityManager.setRealm(userRealm);return securityManager;}// 过滤器@Beanpublic ShiroFilterFactoryBean filterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();// 设置安全管理器bean.setSecurityManager(securityManager);// 定义过滤规则Map<String,String> filterMap = new LinkedHashMap<>();// 无需认证filterMap.put("/","anon");// 需要认证filterMap.put("/index","authc");// 必须有 记住我 功能// filterMap.put("/user/*","user");// 必须有某个资源的权限// filterMap.put("/user/add","perms[user:add]");// 必须有某个角色的权限// filterMap.put("/vip","role");// 设置过滤器bean.setFilterChainDefinitionMap(filterMap);// 设置登录页面访问的请求bean.setLoginUrl("/toLogin");// 未授权访问的请求bean.setUnauthorizedUrl("/unauth");return bean;}
}
Realm
// 自定义 Realm
public class UserRealm extends AuthorizingRealm {// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();// 获取当前用户Subject subject = SecurityUtils.getSubject();User currentUser = (User) subject.getPrincipal();// 查询用户权限并为用户授权info.addStringPermission(currentUser.getPermissions());return info;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;User user = userService.selectUserByName(token.getUsername());if (user == null){// UnknownAccountExceptionreturn null;}// 密码认证,保存用户信息return new SimpleAuthenticationInfo(user,user.getPassword(),"");}
}
controller
@Controller
public class LoginController {@RequestMapping({"/","/toLogin"})public String toLogin(){return "login";}@RequestMapping("/login")public String login(String username, String password, Model model){// 获取当前用户Subject subject = SecurityUtils.getSubject();// 封装用户的登录数据UsernamePasswordToken token = new UsernamePasswordToken(username,password);try {// 执行登录subject.login(token);return "index";} catch (UnknownAccountException e) {model.addAttribute("msg","用户名错误");return "login";} catch (IncorrectCredentialsException e) {model.addAttribute("msg","密码错误");return "login";} catch (AuthenticationException e) {e.printStackTrace();return "login";}}@RequestMapping("/unauth")@ResponseBodypublic String unauth(){return "未授权";}
}