項目環境
- SpringBoot 1.5
- Shiro 權限管理
- vue / axios
部分實現代碼
public Result admLogin(HttpServletRequest request, HttpServletResponse response, String username, String password){
log.info("用戶名:{},密碼:{}",username,password);
if(username.isEmpty() || password.isEmpty()){
return new Result(ResultCode.FAIL);
}
try {
MyFormAuthenticationFilter filter = new MyFormAuthenticationFilter();
MyUsernamePasswordToken upToken = (MyUsernamePasswordToken) filter.createToken(request,response);
Subject subject = SecurityUtils.getSubject();
// 調用subject進行登錄
subject.login(upToken);
return new Result(ResultCode.SUCCESS);
} catch (AuthenticationException e) {
return new Result(ResultCode.FAIL);
}
}
protected AuthenticationToken createToken(ServletRequest request,
ServletResponse response) {
// TODO Auto-generated method stub
String username = getUsername(request);
String password = getPassword(request);
boolean rememberMe = isRememberMe(request);
String host = getHost(request);
return new MyUsernamePasswordToken(username, password, rememberMe,
host, true, roleBase);
}
遇到的問題
在 createToken 方法中,從 request 中獲取到的用戶名和密碼爲 null
解決方案
- axios 默認是 Payload 格式進行數據請求
- 爲 axios 的 post 請求設置請求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
- post 數據請求格式變成了 Form Data,後端就可以從 request 中獲取參數了
說明
這部分說的好像不是很清楚,等我學會了再補充
- 服務端通常是根據請求頭(headers)中的 Content-Type 字段來獲知請求中的消息主體是用何種方式編碼,再對主體進行解析。
- application/x-www-form-urlencoded 這是最常見的 POST 數據提交方式。瀏覽器的原生 form 表單
- Payload 和 Form Data 的主要設置是根據請求頭的 Content-Type 的值來的。
方式 | 請求頭 |
---|---|
Payload | Content-Type: ‘application/json; charset=utf-8’ |
Form Data | Content-Type: ‘application/x-www-form-urlencoded’ |
參考鏈接