SecurityContextHolder.getContext().getAuthentication();为null解决方案
SpringSecurity。之前想用SecurityContextHolder.getContext().getAuthentication()这玩意获取登录后的用户名但是一直空指针。换了各种方案,最后发现是这玩意好像不能放在成员变量的位置,要在方法内部使用。好像是因为这个上下文是和线程相关的。
修改前:
@Api(tags="后台首页")
@RestController
public class IndexController {
Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
@ApiOperation("跳转到后台首页")
@RequestMapping("/")
public String Index(){
return authentication.getName();
// return "/index.html";
}
}
修改后
@Api(tags="后台首页")
@RestController
public class IndexController {
//Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
@ApiOperation("跳转到后台首页")
@RequestMapping("/")
public String Index(){
Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
// return "/index.html";
}
}