在security上下文中没有找到一个认证对象,我这边的问题在于controller中方法添加了认证注解,但是配置类中
源自于一片我为了解决拦截静态文件的博客,上面说这个忽视目录会以classpath中的static文件夹,实际上这样写有着很大问题,这边会让所有的文件不拦截,虽然你的http认证添加了拦截,但是web这个会影响到效果,所以一边允许所有文件不拦截,一边controller中添加了需要认证的注解,所以你一访问就会进去这个页面,但是进去之后发现在security context并没有这个角色值,所以就会出现这个异常
最后对这个异常说明一句话:这个普通来看就是越过了普通的往上下文中添加了角色但是进去了这个页面就会出现这个错误
2.拦截登录之后总是会进login?error,而且没有提示这个情况还是有错误提示才会好解决问题,在http认证配置中的FormLoginConfigurer
添加一个failureUrl("/login/error")
,当然这个地址是我们自己定义的,然后对应的congtroller方法:
@RequestMapping(value = "/login/error")
public void loginError(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
AuthenticationException exception =
(AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
try {
response.getWriter().write(exception.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
这样就可以把最基本的错误打印出来,然后我们再根据实际问题进行处理
3.Spring Security BadCredentialsException这个具体原因还不是很清楚,但是有个很简单的解决办法,把所有的密码加密方式改为相同的,还不可以的话,单独写一个配置类:
@Configuration
public class BeanConfiguration {
/**
* @return Return to the custom password encryptor.
* The reason why it is extracted separately as a configuration class is because if you don’t do this,
* you cannot achieve unified password encryption, which leads to login failures.
* Different password encryption results in different passwords.
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new CustomPasswordEncoder();
}
}
这个CustomPasswordEncoder类是我自己写个一个密码加密类,不想使用的话也可以使用官方推荐的:BCryptPasswordEncoder