shiro 使用者許可權管理(2)-----註冊md5加密,登入驗證
阿新 • • 發佈:2019-01-29
register.jsp註冊頁面:
<body>
<form action="<%=basePath%>/main/add" method="post">
<ul>
<li>姓 名:<input type="text" name="account" /> </li>
<li>密 碼:<input type="text" name="password" /> </li>
<li>暱 稱:<input type ="text" name="nickname" /> </li>
<li><input type="submit" value="註冊" /> </li>
</ul>
</form>
</body>
註冊頁面controller:
@RequestMapping("main")
@Controller
public class RegisterController {
@Autowired
private UserService userService;
@RequestMapping ("register")
public String registerUser(){
return "system/user/register";
}
/**
* 註冊方法,註冊時對密碼進行 MD5演算法加密
* @param user
* @return
*/
@RequestMapping(value = "add",method= RequestMethod.POST)
@ResponseBody
public boolean register(User user){
String password=new SimpleHash("MD5",user.getPassword(),user.getAccount(),2).toHex();
user.setPassword(password);
Role role=new Role();
role.setId((long) 2);
Set<Role> roles=new HashSet<Role>();
roles.add(role);
user.setRoles(roles) ;
return userService.insert(user);
}
}
login.jsp頁面:
<body>
<form action="<%=basePath%>/login" method="post">
<ul>
<li>姓 名:<input type="text" name="account" /> </li>
<li>密 碼:<input type="text" name="password" /> </li>
<li>驗證碼:<input type="text" name="validateCode" />
<img id="validateCodeImg" src=<%=basePath%>/validateCode"/>
<a href="#" onclick="javascript:reloadValidateCode();">看不清?</a></li>
<li><input type="submit" value="確認" /> </li>
</ul>
</form>
</body>
登入頁面controller:
@Controller
public class LoginController {
@RequestMapping(value = "/login" ,method=RequestMethod.POST,
produces={"application/json;charset=UTF-8"})
public String login(User currUser,HttpSession session, HttpServletRequest request){
String code = (String) session.getAttribute("validateCode");
String submitCode = WebUtils.getCleanParam(request, "validateCode");
if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,submitCode.toLowerCase())) {
return "redirect:/";
}
Subject user = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(currUser.getAccount(),
currUser.getPassword());
token.setRememberMe(true);
try {
user.login(token);
return "/system/main";
}catch (AuthenticationException e) {
token.clear();
return "redirect:/";
}
}
/**
* 生成驗證碼
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/validateCode")
public void validateCode(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setHeader("Cache-Control", "no-cache");
String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_ONLY,4,null);
request.getSession().setAttribute("validateCode", verifyCode);
response.setContentType("image/jpeg");
BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 3, true,
Color.WHITE, Color.BLACK, null);
ImageIO.write(bim, "JPEG", response.getOutputStream());
}
}
登入驗證:自定義ShiroDbRealm類
public class ShiroDbRealm extends AuthorizingRealm{
@Resource(name="userService")
private IUserService userService;
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//獲取當前登入的使用者名稱
String account = (String) super.getAvailablePrincipal(principals);
List<String> roles = new ArrayList<String>();
List<String> permissions = new ArrayList<String>();
User user = userService.getByAccount(account);
if(user != null){
if (user.getRoles() != null && user.getRoles().size() > 0) {
for (Role role : user.getRoles()) {
roles.add(role.getName());
if (role.getPmss() != null && role.getPmss().size() > 0) {
for (Permission pmss : role.getPmss()) {
if(!StringUtils.isEmpty(pmss.getPermission())){
permissions.add(pmss.getPermission());
}
}
}
}
}
}else{
throw new AuthorizationException();
}
//給當前使用者設定角色
info.addRoles(roles);
//給當前使用者設定許可權
info.addStringPermissions(permissions);
return info;
}
/**
* 認證回撥函式,登入時呼叫.
*/
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
User user = userService.getByAccount(token.getUsername());
if (user != null) {
Object principal=token.getUsername();
String credentials=user.getPassword();
String realName=getName();//暫時不太明白這個什麼意思
ByteSource credentialsSalt=ByteSource.Util.bytes(user.getAccount());
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal,credentials,
credentialsSalt,realName);
return info;
} else {
return null;
}
}