直接写死用户名和密码,也不需要创建用户表
@Configuration
@EnableWebSecurity
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");
}
}
调用结果
点击下面的cookies会发现,token默认存到了浏览器的缓存里。
这种方式比较简单,适合一个项目需要一个登录入口,但用户不能创建账号,只能有开发人员决定用户的信息,一个或者几个用户信息直接写死正在程序里。