maven spring hibernate shiro

maven spring hibernate RBAC shiro mysql java

代碼發佈於 http://git.oschina.net/alexgaoyh/alexgaoyh mysql


1:數據庫表結構設計採用RBAC權限模型,即五張表結構設計(用戶,角色,用戶-角色,權限,角色-權限),本文再也不詳細說明; git


2:shiro使用過程當中: spring

2.1:如下這個類是進行用戶的數據庫驗證的,從數據庫裏面查出是否有這個用戶。
sql

public class ShiroDbRealm extends AuthorizingRealm
須要注意的是 doGetAuthenticationInfo 方法的

return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getPassword()),getName()); 部分; 數據庫


2.2: 在生成對用表結構的時候,須要注意本例中的user表中password字段使用了MD5加密, maven

因此,在生成表結構以後,執行如下方法生成對應的用戶數據: 加密

public String saveSysmanUserEntity() throws Exception{
    	SysmanUser su = new SysmanUser();
    	su.setUserName("admin");
    	su.setRealName("admim");
    	su.setPassword(new Md5Hash("admin").toHex());
    	su.setStatus(SysmanUser.STATUS_NORMAL);
    	sysmanUserService.saveOrUpdate(su);
    	return JSONObject.valueToString(su);
    }
2.3: 同時在登錄方法中

public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) {

		Map<String, Boolean> map = new HashMap<String, Boolean>();
		
		boolean loginStatus = false;
		boolean captchaStatus = false;
		
		String captcha = request.getParameter("captcha");
		String exitCode = (String) request.getSession().getAttribute(CaptchaConstant.KEY_CAPTCHA);
		if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) {
			System.out.println("驗證碼錯誤");
		}else{
			captchaStatus = true;
			
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			
			Md5Hash md5Hash = new Md5Hash(password);
			
			UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toHex());
			
			System.out.println(token.getUsername());
			System.out.println(token.getPassword());
			
			try {
				Subject subject = SecurityUtils.getSubject();
				subject.login(token);
				token.clear();
				SysmanUser user = (SysmanUser) subject.getPrincipal();
				subject.getSession().setAttribute("adminCurrentUser", user);
				loginStatus = true;
				
			} catch (UnknownAccountException ex) {
				ex.printStackTrace();
				
			} catch (IncorrectCredentialsException ex) {
				ex.printStackTrace();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		
		map.put("loginStatus", loginStatus);
		map.put("captchaStatus", captchaStatus);
		
		ModelAndView mav = new ModelAndView("views/admin/index", map);

		return mav;
	}
須要注意用戶輸入的password是明文,在生成token的時候,須要進行以下操做:

Md5Hash md5Hash = new Md5Hash(password);
			
UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toHex());
相關文章
相關標籤/搜索