第一步:前端表单
<form action="/login" method="post">
用户名:<input type="text" name="userName">
密码:<input type="password" name="userPassword">
<input type="submit" value="login">
</form>
第二步:后端controller
@RequestMapping("/login")
public String myTranslate3(String userName,String userPassword) {
System.out.println(userName+":"+userPassword);
//获取用户主体subject
Subject subject = SecurityUtils.getSubject();
//封装用户数据 (将前端传入的数据封装成登录令牌)
UsernamePasswordToken token = new UsernamePasswordToken(userName, userPassword);
//指定登录方法
try {
//传入令牌进行登录
subject.login(token);
}catch (UnknownAccountException e){
//用户名不存在
System.out.println("用户名不存在");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
return "error";
}
return "index";
}
第三步:自定义realm进行授权
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
/**
* 认证
* @param authenticationToken 令牌
* @return 用户信息
* @throws
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
//从数据库中取出用户
User user = userService.getUserByName(token.getUsername());
System.out.println(user);
//判断用户名是否存在
if (user !=null){
if (!token.getUsername().equals(user.getUserName())){
//用户名不存在
return null;
}
//判断密码
return new SimpleAuthenticationInfo("",user.getUserPassword(),"");
}else {
return null;
}
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("指定了授权");
return null;
}
}