在配置SpringSecurity的项目中,通过配置.authorizeRequests().antMathers("/path/**",....)
来设置哪些路径需要用户权限,哪些可以不登录浏览。但是如果在该项目中部署了Angular2单页应用的话,由于对SpringSecurity来说仅在第一次进入Angular2应用时经过了Security拦截,之后所有的页面跳转均在Angular2的路由管理下完成,因此SpringSecurity无法管理Angular2应用内部的页面权限,此时需要对Angular2的路由进行改造,让Angular2的路由实现类似Security的功能。
登录接口改造
SpringSecurity改造
默认情况下,SpringSecurity通过设置.formLogin()
来定义登录页入口,最后通过登录页的表单提交完成验证,并跳转至首页。在Angular2项目中,若登录页也由Angular2管理,则登录过程需要通过ajax调用接口实现。因此需要自定义一个登录接口完成登录页post表单登录的流程。
通过AuthenticationManager
即可调用内部的验证流程。
代码如下
@Autowired
AuthenticationManager authenticationManager;
@ResponseBody
@RequestMapping(value="doLogin",method = RequestMethod.POST)
public ResultBean doLogin(HttpServletRequest request, HttpServletResponse response,
@RequestParam("userName")String userName,@RequestParam("password") String password){
ResultBean bean = new ResultBean();
try {
// 内部登录请求
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
// 验证
Authentication auth = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(auth);
bean.setReturnCode(1);
} catch (AuthenticationException e) {
bean.setReturnCode(0);
bean.setReturnMsg(e.getMessage());
}
return bean;
}
Angular2登录
在合适的位置编写登录函数,提交一个http请求即可。<