Spring Boot 整合 Shiro实现认证及授权管理 (2)

authc: 需要认证才能进行访问

认证和授权 @Slf4j public class AuthRealm extends AuthorizingRealm { @Resource private UserInfoService userInfoService; /** * 授权 * * @param principals * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { log.info("调用授权方法"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal(); for (SysRole role : userInfo.getRoleList()) { authorizationInfo.addRole(role.getRole()); for (SysPermission p : role.getPermissions()) { authorizationInfo.addStringPermission(p.getPermission()); } } return authorizationInfo; } /** * 认证(主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确) * * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { log.info("调用认证方法"); //获取用户的输入的账号. String username = (String) token.getPrincipal(); if (username == null) { throw new AuthenticationException("账号名为空,登录失败!"); } log.info("credentials:" + token.getCredentials()); UserInfo userInfo = userInfoService.findByUsername(username); if (userInfo == null) { throw new AuthenticationException("不存在的账号,登录失败!"); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo, //用户 userInfo.getPassword(), //密码 ByteSource.Util.bytes(userInfo.getCredentialsSalt()), //加盐后的密码 getName() //指定当前 Realm 的类名 ); return authenticationInfo; } } 登录 /** * 登录 * * @param username * @param password * @param map 如果出错,回传给前端的map * @return */ @RequestMapping("/login") public String login(String username, String password, Map<String, Object> map) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); String msg = ""; try { subject.login(token); } catch (UnknownAccountException e) { msg = "账号不存在!"; } catch (DisabledAccountException e) { msg = "账号未启用!"; } catch (IncorrectCredentialsException e) { msg = "密码错误!"; } catch (Throwable e) { msg = "未知错误!"; } //判断登录是否出现错误 if (msg.length() > 0) { map.put("msg", msg); return "/login"; } else { return "redirect:index"; } } 方法增加权限验证 /** * 用户添加 * * @return */ @RequestMapping("/userAdd") @RequiresPermissions("userInfo:add") public String userInfoAdd() { return "userInfoAdd"; }

这样配置完,执行程序。只有用户拥有userAdd权限才允许访问userAdd接口,否则会提示“未授权”访问

资料

示例代码-github

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyygdp.html