springmvc+shiro+maven 实现登录认证与权限授权管理

网友投稿 312 2023-04-01


springmvc+shiro+maven 实现登录认证与权限授权管理

Shiro 是Shiro 是一个 Apache 下的一开源项目项目,旨在简化身份验证和授权。

1:shiro的配置,通过maven加入shiro相关jar包

org.apache.shiro

shiro-core

1.2.1

org.apache.shiro

shiro-web

1.2.1

org.apache.shiro

shiro-ehcache

1.2.1

org.apache.shiro

shiro-spring

1.2.1

2 :在web.xml中添加shiro过滤器

shiroFilter

org.springframework.web.filter.DelegatingFilterProxy

shiroFilter

/admin/*

3: springmvc中对shiro配置

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:context="http://springframework.org/schema/context"

xmlns:aop="http://springframework.org/schema/aop" xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-3.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.2.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-3.2.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-3.2.xsd ">

/images/** = anon

/js/** = anon

/styles/** = anon

/validatecode.jsp = anon

/admin/logout.do = logout

/welcome.jsp = user

/admin/index.do = user

/** = authc

class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">

class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter ">

class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:context="http://springframework.org/schema/context"

xmlns:aop="http://springframework.org/schema/aop" xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-3.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.2.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-3.2.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-3.2.xsd ">

/images/** = anon

/js/** = anon

/styles/** = anon

/validatecode.jsp = anon

/admin/logout.do = logout

/welcome.jsp = user

/admin/index.do = user

/** = authc

class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">

class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">

class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter ">

class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter ">

class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">

class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">

4 :自定义Realm编码

public class CustomRealm extends AuthorizingRealm {

// 设置realm的名称

@Override

public void setName(String name) {

super.setName("customRealm");

}

@Autowired

private AdminUserService adminUserService;

/**

* 认证

*/

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

// token中包含用户输入的用户名和密码

// 第一步从token中取出用户名

String userName = (String) token.getPrincipal();

// 第二步:根据用户输入的userCode从数据库查询

TAdminUser adminUser = adminUserService.getAdminUserByUserName(userName);

// 如果查询不到返回null

if (adminUser == null) {//

return null;

}

// 获取数据库中的密码

String password = adminUser.getPassword();

/**

* 认证的用户,正确的密码

*/

AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName());

//MD5 加密+加盐+多次加密

//SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password,ByteSource.Util.bytes(salt), this.getName());

return authcInfo;

}

/**

* 授权,只有成功通过doGetAuthenticationInfo方法的认证后才会执行。

*/

@Override

jSCBmfprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

// 从 principals获取主身份信息

// 将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),

TAdminUser activeUser = (TAdminUser) principals.getPrimaryPrincipal();

// 根据身份信息获取权限信息

// 从数据库获取到权限数据

TAdminRole adminRoles = adminUserService.getAdminRoles(activeUser);

// 单独定一个集合对象

List permissions = new ArrayList();

if (adminRoles != null) {

permissions.add(adminRoles.getRoleKey());

}

// 查到权限数据,返回授权信息(要包括 上边的permissions)

SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

// 将上边查询到授权信息填充到simpleAuthorizationInfo对象中

simpleAuthorizationInfo.addStringPermissions(permissions);

return simpleAuthorizationInfo;

}

// 清除缓存

public void clearCached() {

PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();

super.clearCache(principals);

}

}

5 缓存配置

ehcache.xml代码如下:

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

overflowToDisk="false"

diskPersistent="false"

diskExpiryThreadIntervalSeconds="120"

/>

通过使用ehache中就避免第次都向服务器发送权限授权(doGetAuthorizationInfo)的请求。

6.自定义表单编码过滤器

CustomFormjSCBmfAuthenticationFilter代码,认证之前调用,可用于验证码校验

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

// 原FormAuthenticationFilter的认证方法

@Override

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

// 在这里进行验证码的校验

// 从session获取正确验证码

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

HttpSession session = httpServletRequest.getSession();

// 取出session的验证码(正确的验证码)

String validateCode = (String) session.getAttribute("validateCode");

// 取出页面的验证码

// 输入的验证和session中的验证进行对比

String randomcode = httpServletRequest.getParameter("randomcode");

if (randomcode != null && validateCode != null && !randomcode.equals(validateCode)) {

// 如果校验失败,将验证码错误失败信息,通过shiroLoginFailure设置到request中

httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");

// 拒绝访问,不再校验账号和密码

return true;

}

return super.onAccessDenied(request, response);

}

}

在此符上验证码jsp界面的代码  validatecode.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ page import="java.util.Random"%>

<%@ page import="java.io.OutputStream"%>

<%@ page import="java.awt.Color"%>

<%@ page import="java.awt.Font"%>

<%@ page import="java.awt.Graphics"%>

<%@ page import="java.awt.image.BufferedImage"%>

<%@ page import="javax.imageio.ImageIO"%>

<%

int width = 60;

int height = 32;

//create the imagjSCBmfe

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

// set the background color

g.setColor(new Color(0xDCDCDC));

g.fillRect(0, 0, width, height);

// draw the border

g.setColor(Color.black);

g.drawRect(0, 0, widthjSCBmf - 1, height - 1);

// create a random instance to generate the codes

Random rdm = new Random();

String hash1 = Integer.toHexString(rdm.nextInt());

// make some confusion

for (int i = 0; i < 50; i++) {

int x = rdm.nextInt(width);

int y = rdm.nextInt(height);

g.drawOval(x, y, 0, 0);

}

// generate a random code

String capstr = hash1.substring(0, 4);

//将生成的验证码存入session

session.setAttribute("validateCode", capstr);

g.setColor(new Color(0, 100, 0));

g.setFont(new Font("Candara", Font.BOLD, 24));

g.drawString(capstr, 8, 24);

g.dispose();

//输出图片

response.setContentType("image/jpeg");

out.clear();

out = pageContext.pushBody();

OutputStream strm = response.getOutputStream();

ImageIO.write(image, "jpeg", strm);

strm.close();

%>

7.登录控制器方法

/**

* 到登录界面

*

* @return

* @throws Exception

*/

@RequestMapping("login.do")

public String adminPage(HttpServletRequest request) throws Exception {

// 如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名

String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");

// 根据shiro返回的异常类路径判断,抛出指定异常信息

if (exceptionClassName != null) {

if (UnknownAccountException.class.getName().equals(exceptionClassName)) {

// 最终会抛给异常处理器

throw new CustomJsonException("账号不存在");

} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {

throw new CustomJsonException("用户名/密码错误");

} else if ("randomCodeError".equals(exceptionClassName)) {

throw new CustomJsonException("验证码错误 ");

} else {

throw new Exception();// 最终在异常处理器生成未知错误

}

}

// 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径

// 登陆失败还到login页面

return "admin/login";

}

8.用户回显Controller

当用户登录认证成功后,CustomRealm在调用完doGetAuthenticationInfo时,通过

AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName());

return authcInfo;

SimpleAuthenticationInfo构造参数的第一个参数传入一个用户的对象,之后,可通过Subject subject = SecurityUtils.getSubject();中的subject.getPrincipal()获取到此对象。所以需要回显用户信息时,我这样调用的

@RequestMapping("index.do")

public String index(Model model) {

//从shiro的session中取activeUser

Subject subject = SecurityUtils.getSubject();

//取身份信息

TAdminUser adminUser = (TAdminUser) subject.getPrincipal();

//通过model传到页面

model.addAttribute("adminUser", adminUser);

return "admin/index";

}

9.在jsp页面中控制权限

先引入shiro的头文件

<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>

采用shiro标签对权限进行处理


我拥有超级的增删改查权限额

10.在Controller控制权限

通过@RequiresPermissions注解,指定执行此controller中某个请求方法需要的权限

@RequestMapping("/queryInfo.do")

@RequiresPermissions("q")//执行需要"q"权限

public ModelAndView queryItems(HttpServletRequest request) throws Exception { }

11.MD5加密加盐处理

这里以修改密码为例,通过获取新的密码(明文)后通过MD5加密+加盐+3次加密为例

@RequestMapping("updatePassword.do")

@ResponseBody

public String updateAdminUserPassword(String newPassword) {

// 从shiro的session中取activeUser

Subject subject = SecurityUtils.getSubject();

// 取身份信息

TAdminUser adminUser = (TAdminUser) subject.getPrincipal();

// 生成salt,随机生成

SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();

String salt = secureRandomNumberGenerator.nextBytes().toHex();

Md5Hash md5 = new Md5Hash(newPassword, salt, 3);

String newMd5Password = md5.toHex();

// 设置新密码

adminUser.setPassword(newMd5Password);

// 设置盐

adminUser.setSalt(salt);

adminUserService.updateAdminUserPassword(adminUser);

return newPassword;

}

总结

以上所述是给大家介绍的springmvc+shiro+maven 实现登录认证与权限授权管理,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

overflowToDisk="false"

diskPersistent="false"

diskExpiryThreadIntervalSeconds="120"

/>

通过使用ehache中就避免第次都向服务器发送权限授权(doGetAuthorizationInfo)的请求。

6.自定义表单编码过滤器

CustomFormjSCBmfAuthenticationFilter代码,认证之前调用,可用于验证码校验

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

// 原FormAuthenticationFilter的认证方法

@Override

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

// 在这里进行验证码的校验

// 从session获取正确验证码

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

HttpSession session = httpServletRequest.getSession();

// 取出session的验证码(正确的验证码)

String validateCode = (String) session.getAttribute("validateCode");

// 取出页面的验证码

// 输入的验证和session中的验证进行对比

String randomcode = httpServletRequest.getParameter("randomcode");

if (randomcode != null && validateCode != null && !randomcode.equals(validateCode)) {

// 如果校验失败,将验证码错误失败信息,通过shiroLoginFailure设置到request中

httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");

// 拒绝访问,不再校验账号和密码

return true;

}

return super.onAccessDenied(request, response);

}

}

在此符上验证码jsp界面的代码  validatecode.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ page import="java.util.Random"%>

<%@ page import="java.io.OutputStream"%>

<%@ page import="java.awt.Color"%>

<%@ page import="java.awt.Font"%>

<%@ page import="java.awt.Graphics"%>

<%@ page import="java.awt.image.BufferedImage"%>

<%@ page import="javax.imageio.ImageIO"%>

<%

int width = 60;

int height = 32;

//create the imagjSCBmfe

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

// set the background color

g.setColor(new Color(0xDCDCDC));

g.fillRect(0, 0, width, height);

// draw the border

g.setColor(Color.black);

g.drawRect(0, 0, widthjSCBmf - 1, height - 1);

// create a random instance to generate the codes

Random rdm = new Random();

String hash1 = Integer.toHexString(rdm.nextInt());

// make some confusion

for (int i = 0; i < 50; i++) {

int x = rdm.nextInt(width);

int y = rdm.nextInt(height);

g.drawOval(x, y, 0, 0);

}

// generate a random code

String capstr = hash1.substring(0, 4);

//将生成的验证码存入session

session.setAttribute("validateCode", capstr);

g.setColor(new Color(0, 100, 0));

g.setFont(new Font("Candara", Font.BOLD, 24));

g.drawString(capstr, 8, 24);

g.dispose();

//输出图片

response.setContentType("image/jpeg");

out.clear();

out = pageContext.pushBody();

OutputStream strm = response.getOutputStream();

ImageIO.write(image, "jpeg", strm);

strm.close();

%>

7.登录控制器方法

/**

* 到登录界面

*

* @return

* @throws Exception

*/

@RequestMapping("login.do")

public String adminPage(HttpServletRequest request) throws Exception {

// 如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名

String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");

// 根据shiro返回的异常类路径判断,抛出指定异常信息

if (exceptionClassName != null) {

if (UnknownAccountException.class.getName().equals(exceptionClassName)) {

// 最终会抛给异常处理器

throw new CustomJsonException("账号不存在");

} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {

throw new CustomJsonException("用户名/密码错误");

} else if ("randomCodeError".equals(exceptionClassName)) {

throw new CustomJsonException("验证码错误 ");

} else {

throw new Exception();// 最终在异常处理器生成未知错误

}

}

// 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径

// 登陆失败还到login页面

return "admin/login";

}

8.用户回显Controller

当用户登录认证成功后,CustomRealm在调用完doGetAuthenticationInfo时,通过

AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName());

return authcInfo;

SimpleAuthenticationInfo构造参数的第一个参数传入一个用户的对象,之后,可通过Subject subject = SecurityUtils.getSubject();中的subject.getPrincipal()获取到此对象。所以需要回显用户信息时,我这样调用的

@RequestMapping("index.do")

public String index(Model model) {

//从shiro的session中取activeUser

Subject subject = SecurityUtils.getSubject();

//取身份信息

TAdminUser adminUser = (TAdminUser) subject.getPrincipal();

//通过model传到页面

model.addAttribute("adminUser", adminUser);

return "admin/index";

}

9.在jsp页面中控制权限

先引入shiro的头文件

<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>

采用shiro标签对权限进行处理


我拥有超级的增删改查权限额

10.在Controller控制权限

通过@RequiresPermissions注解,指定执行此controller中某个请求方法需要的权限

@RequestMapping("/queryInfo.do")

@RequiresPermissions("q")//执行需要"q"权限

public ModelAndView queryItems(HttpServletRequest request) throws Exception { }

11.MD5加密加盐处理

这里以修改密码为例,通过获取新的密码(明文)后通过MD5加密+加盐+3次加密为例

@RequestMapping("updatePassword.do")

@ResponseBody

public String updateAdminUserPassword(String newPassword) {

// 从shiro的session中取activeUser

Subject subject = SecurityUtils.getSubject();

// 取身份信息

TAdminUser adminUser = (TAdminUser) subject.getPrincipal();

// 生成salt,随机生成

SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();

String salt = secureRandomNumberGenerator.nextBytes().toHex();

Md5Hash md5 = new Md5Hash(newPassword, salt, 3);

String newMd5Password = md5.toHex();

// 设置新密码

adminUser.setPassword(newMd5Password);

// 设置盐

adminUser.setSalt(salt);

adminUserService.updateAdminUserPassword(adminUser);

return newPassword;

}

总结

以上所述是给大家介绍的springmvc+shiro+maven 实现登录认证与权限授权管理,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Boot启动流程分析
下一篇:java 设计模式之单例的实例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~