import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShiroController {
protected final static Logger logger = LogManager.getLogger(ShiroController.class);
/**
* 身份验证
* @param username
* @param password
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("phone") String phone, @RequestParam("password") String password) {
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(phone, password);
// 执行认证登陆
try {
subject.login(token);
} catch (UnknownAccountException uae) {
return "未知账户";
} catch (IncorrectCredentialsException ice) {
return "密码不正确";
} catch (LockedAccountException lae) {
return "账户已锁定";
} catch (ExcessiveAttemptsException eae) {
return "用户名或密码错误次数过多";
} catch (AuthenticationException ae) {
return "用户名或密码不正确!";
}
if (subject.isAuthenticated()) {
return "登录成功";
} else {
token.clear();
return "登录失败";
}
}
/**
* 退出登录
* @return
*/
@RequestMapping(value="logout",method=RequestMethod.GET)
public String logout(){
Subject subject = SecurityUtils.getSubject();
try {
subject.logout();
} catch (Exception e) {
logger.error("errorMessage:" + e.getMessage());
}
return "退出成功";
}
}
shiro的身份登录
于 2019-11-06 18:18:12 首次发布
511

被折叠的 条评论
为什么被折叠?



