spring security登录验证(方式一)

直接写死用户名和密码,也不需要创建用户表

@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默认存到了浏览器的缓存里。
这种方式比较简单,适合一个项目需要一个登录入口,但用户不能创建账号,只能有开发人员决定用户的信息,一个或者几个用户信息直接写死正在程序里。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值