springboot +vue (从零开始)——五:spring boot 登录(一)

书接上回:

springboot +vue (从零开始)——四:spring boot 创建项目

第一步:

用户表中 实现 userDetails

实现里面的方法
在这里插入图片描述

方法中有详细的备注,默认时是false, 需要改成 true

第二步:

创建 HrService 同样继承 userDetailService 并实现里面的方法

在这里插入图片描述

在这里插入图片描述

HrMapper.xml

<resultMap id="BaseResultMap" type="fun.codefarmer.pm.model.Hr" >
 <id column="id" property="id" jdbcType="INTEGER" />
 <result column="name" property="name" jdbcType="VARCHAR" />
 <result column="phone" property="phone" jdbcType="CHAR" />
 <result column="telephone" property="telephone" jdbcType="VARCHAR" />
 <result column="address" property="address" jdbcType="VARCHAR" />
 <result column="enabled" property="enabled" jdbcType="BIT" />
 <result column="username" property="username" jdbcType="VARCHAR" />
 <result column="password" property="password" jdbcType="VARCHAR" />
 <result column="userface" property="userface" jdbcType="VARCHAR" />
 <result column="remark" property="remark" jdbcType="VARCHAR" />
</resultMap>
<select id="loadUserByUsername" resultMap="BaseResultMap">
select * from hr where username = #{username}
</select>

添加 sercurity 配置

在这里插入图片描述

接下来 我们先测试下。

在这里插入图片描述

接下来我们 在hr 表里加入一条数据,手动创建一个用户,密码是 123 下面是加密后的密码,存入库中

$2a$10$3MhfCTCMQuiGSrzxHYBZ7eXvnn.Eh5VmjNvosqV7SC/W4cg6XFDOi
在这里插入图片描述

启动项目

浏览器输入:http://127.0.0.1:8080/first/hello

会跳出以下页面

在这里插入图片描述

输入账号:admin 密码:123

在这里插入图片描述

显示这个 ,那么恭喜你,你已经成功了。

在这里插入图片描述

这个页面是账号密码错误。

BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode("123");
System.out.println(encode);

上面的3行代码,找个main方法执行下。生成的就是加密后的密码。存入数据库password字段

下面进行新的配置 在 SecurityConfig 中加入下面的方法。同时加个新建的返回类 RespBean

package fun.codefarmer.pm.model;

/**
* @ ClassName RespBean
* @ Descriotion TODO
* @ author codeFarmer_z
* @ 公众号:码农教程
* @ Date 2022/3/19 22:06
**/
public class RespBean {
   private Integer status;
   private String msg;
   private Object object;

   public static RespBean ok(String msg) {
       return new RespBean(200,msg,null);
  }
   public static RespBean ok(String msg,Object o) {
       return new RespBean(200,msg,o);
  }
   public static RespBean error(String msg) {
       return new RespBean(500,msg,null);
  }
   public static RespBean error(String msg,Object o) {
       return new RespBean(500,msg,o);
  }
   private RespBean() {

  }

   public RespBean(Integer status, String msg, Object object) {
       this.status = status;
       this.msg = msg;
       this.object = object;
  }

   public Integer getStatus() {
       return status;
  }

   public void setStatus(Integer status) {
       this.status = status;
  }

   public String getMsg() {
       return msg;
  }

   public void setMsg(String msg) {
       this.msg = msg;
  }

   public Object getObject() {
       return object;
  }

   public void setObject(Object object) {
       this.object = object;
  }
}
@Override
   protected void configure(HttpSecurity http) throws Exception {

       http.authorizeRequests()
              .anyRequest().authenticated()
              .and()
              .formLogin()
              .usernameParameter("username")
              .passwordParameter("password")
              .loginProcessingUrl("/doLogin")
              .loginPage("/login")
              .successHandler(new AuthenticationSuccessHandler() {// 登陆成功的回调
                   @Override
                   public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                       resp.setContentType("application/json;charset=utf-8");
                       resp.getWriter();
                       PrintWriter out =  resp.getWriter();
                       Hr hr = (Hr) authentication.getPrincipal();//登录用户的信息存在authentication中,取出,并强转成hr对象
                       hr.setPassword(null);
                       RespBean ok = RespBean.ok("登录成功", hr);
                       //String s = new ObjectMapper().writeValueAsString(hr);//登录成功后的用户转成字符串,这里时返回的respBean 信息
                       String s = new ObjectMapper().writeValueAsString(ok);
                       out.write(s);//写出去
                       out.flush();
                       out.close();
                  }
              })
              .failureHandler(new AuthenticationFailureHandler() {// 登录失败的回调
                   @Override
                   public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                       response.setContentType("application/json;charset=utf-8");//设置相应头为json格式
                       response.getWriter();
                       PrintWriter out =  response.getWriter();
                       RespBean respBean = RespBean.error("登录失败");
                       if (exception instanceof LockedException){
                           respBean.setMsg("账户被锁定,请联系管理员!");
                      } else if (exception instanceof CredentialsExpiredException){
                           respBean.setMsg("密码过期,请联系管理员");
                      } else if (exception instanceof AccountExpiredException){
                           respBean.setMsg("账户过期,请联系管理员");
                      } else if (exception instanceof DisabledException){
                           respBean.setMsg("账户被禁用,请联系管理员");
                      } else if (exception instanceof BadCredentialsException){
                           respBean.setMsg("用户名或密码错误");
                      }
                       out.write(new ObjectMapper().writeValueAsString(respBean));//写出去
                       out.flush();
                       out.close();
                  }
              })
              .permitAll()
              .and()
              .logout()
              .logoutSuccessHandler(new LogoutSuccessHandler() {
                   @Override
                   public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                  }
              })
              .permitAll()
              .and()
              .csrf().disable();
  }

上面全部完事,重新启动项目

postman 调试

http://127.0.0.1:8080/doLogin

在这里插入图片描述

今天先写到这里,大家给个关注!您觉得好,分享给朋友这里感谢各位!
截止目前之所以使用截图多,主要是怕各位找不到具体位置。等到后期所有类都出现了。截图就少了。
今天就到这里了。如果大家有什么想知道的。可以留言,
感谢有缘人,感谢关注!感谢分享!

在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值