用户认证
1.在单体项目中如何实现用户认证?
在单体项目中如何保证受限资源在用户未登录的情况下不允许访问?
单体项目中,视图资源(页面)和接口(控制器)在一台服务器中,用户的多次请求都会基于同一个回话(session) ,因此可以借助session来进行用户认证判断。
- 当用户登录成功后,将用户信息存放到session,
- 当用户再次访问受限资源,验证session中是否存在用户信息,可以根据session有无用户信息来判断用户是否登录 。
2.前后端分离开发项目中如何实现用户认证?
基于token的用户认证的实现
-
登录认证接口生成token public class UsersController {
@Resource
private UserService userService;
@ApiOperation("用户登录接口")
@ApiImplicitParams({
@ApiImplicitParam(dataTypeClass = String.class,name = "username", value = "用户登录账号",required = true),
@ApiImplicitParam(dataTypeClass = String.class,name = "password", value = "用户登录密码",required = true)
})
@GetMapping("/login")
public ResultVO login(@RequestParam("username") String name,
@RequestParam(value = "password") String pwd){
ResultVO resultVO = userService.checkLogin(name, pwd);
return resultVO;
}
}
public class UserServiceImpl implements UserService {
@Autowired
private UsersMapper usersMapper;
@Override
public ResultVO checkLogin(String name, String pwd) {
Example example = new Example(Users.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username",name);
List<Users> users = usersMapper.selectByExample(example);
if(users.size() == 0){
return new ResultVO(ResStatus.NO,"登录失败,用户名不存在",null);
}else{
String md5Pwd = MD5Utils.md5(pwd);
if(md5Pwd.equals(users.get(0).getPassword())){
String token = Base64Utils.encode(name+123456);
return new ResultVO(ResStatus.OK,token,users.get(0));
}else{
return new ResultVO(ResStatus.NO,"登录失败,密码错误",null);
}
}
}
} ```
-
登录页面接受到token,并且存储到cookie中 token的工具js var operator = "=";
function getCookieValue(keyStr){
var value = null;
var s = window.document.cookie;
var arr = s.split("; ");
for(var i=0; i<arr.length; i++){
var str = arr[i];
var k = str.split(operator)[0];
var v = str.split(operator)[1];
if(k == keyStr){
value = v;
break;
}
}
return value;
}
function setCookieValue(key,value){
document.cookie = key+operator+value;
}
前端将token存到cookie中 doSubmit:function(){
if(vm.isRight){
var url = "http://localhost:8888/user/login";
axios.get(url,{
params:{username:vm.username,password:vm.password}
}).then((res)=>{
console.log(res)
//res.data 才表示接口返回的数据
var vo = res.data;
console.log(vo);
if(vo.code == 10000){
//如果登陆成功就把token存放到cookie
setCookieValue("token",vo.msg);
window.location.href = "index.html";
}else{
vm.tips = "登录失败,账号或密码错误!";
}
});
}else{
vm.tips = "请正确输入帐号和密码!";
}
- 在index.html 页面中获取token
|