前一段时间整合了一下SpringBoot+SpringSecurity+JWT,整合时JWT还好说,但是SpringSecurity出现的问题比较多,下面上源码图
这里SpringSecurity中设定死了登录时的用户名和密码的key
为username和password,
还有表单的提交路径和请求方式都固定了,但是表单提交时的路径可以通过
这里修改,还有别的问题,但是由于时间不充裕,以后有时间补上,文章末尾会提供此处代码
/**
* @Description: SpringSecurity配置类
* @Author: 臧东运
* @CreateTime: 2019/4/15 17:15
*/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtUserDetailsService userDetailsService; // 用户权限认证
@Autowired
private PasswordEncoder passwordEncoder; // 密码编码
@Autowired
private JwtAuthenticationEntryPoint authenticationEntryPoint; // 未登陆
@Autowired
private JwtAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功
@Autowired
private JwtAuthenticationFailureHandler authenticationFailureHandler; // 登录失败
@Autowired
private JwtLogoutSuccessHandler logoutSuccessHandler; // 注销成功
@Autowired
private JwtAccessDeniedHandler accessDeniedHandler; // 无权访问
@Value("${jwt.exceptUrl}")
private String exceptUrl; // 从配置文件中读取
@Value("${jwt.loginUrl}")
private String loginUrl;
@Value("${jwt.indexUrl}")
private String indexUrl;
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
// 加入自定义的安全认证
authenticationManagerBuilder
// .inMemoryAuthentication() // 生成缓存数据
// .withUser("111").password(passwordEncoder.encode("111")).roles("USER","ADMIN")
// .and()
// .withUser("222").password(passwordEncoder.encode("222")).roles("USER")
// .and()
// .withUser("333").password("333").roles("ADMIN");
// 设置UserDetailsService
.userDetailsService(userDetailsService)
// 使用BCrypt进行密码的hash
.passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 由于使用的是JWT,我们这里不需要csrf
.csrf().disable()
.authorizeRequests()
// 允许无授权访问
.antMatchers(exceptUrl).permitAll()
.antMatchers(loginUrl,"/js/**","/css/**","/noauth/index.html").permitAll()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated().and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin().loginPage(loginUrl) //开启登录
.loginProcessingUrl("/login").permitAll()//指定自定义form表单请求的路径
.successHandler(authenticationSuccessHandler) // 登录成功
.failureHandler(authenticationFailureHandler) // 登录失败
.permitAll().and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.permitAll().and();
// 基于token,所以不需要session
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();
// 禁用缓存
// httpSecurity.headers().cacheControl();
}
}
如果发现什么问题请留言,毕竟代码都是人写的难免会出错。