基于springsession存储token并将token放置在header中
1、加依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
2、写配置文件
@Configuration
@EnableWebSecurity
@EnableSpringHttpSession
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* Http请求处理
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//设置所有人可以访问登录页
.antMatchers("/").permitAll()
.and().authorizeRequests()
.anyRequest().permitAll()
.and().formLogin()
.loginPage("/").permitAll()
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter writer = response.getWriter();
JSONObject jsonObject = new JSONObject();
if (exception instanceof DisabledException) {
jsonObject.put("message", "账户被禁用,请联系管理员!");
} else if (exception instanceof BadCredentialsException) {
jsonObject.put("message", "用户名或密码错误!");
}
writer.write(jsonObject.toJSONString());
writer.flush();
writer.close();
}
}).successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//返回给前端的json对象,也可不返回
PrintWriter writer = response.getWriter();
writer.write(JSONObject.toJSONString(new JsonInfo(request.getSession().getId())));
writer.flush();
writer.close();
//清除session中的认证信息
clearAuthenticationAttributes(request);
}
})
//暂时禁用csrf
.and().csrf().disable();
}
//清除session中的认证信息
private void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private class JsonInfo {
private String token;
}
/**
* 授权验证服务
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
//设置编码器
.passwordEncoder(NoOpPasswordEncoder.getInstance())
//添加测试用户和密码
.withUser("123456").password("123456").roles("USER");
}
@Bean
//将token存放到header里,不加这个方法header里就没x-auth-token参数
public HeaderHttpSessionIdResolver httpSessionStrategy() {
return new HeaderHttpSessionIdResolver("x-auth-token");
}
//存session时要时用到
@Bean
public MapSessionRepository sessionRepository() {
return new MapSessionRepository(new ConcurrentHashMap<>());
}
}
3、调试结果