springboot2.2.2+springSecurity+mybatis(一) 基于内存认证

依赖

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

自定义类继承WebSecurityConfigurerAdapter,并重写了2个configure方法(分别是认证方法和授权方法)
不对密码进行加密,但是必须指定一个PasswordEncoder,不然报PasswordEncoder错!


@Bean
    PasswordEncoder passwordEncoder(){
         return NoOpPasswordEncoder.getInstance();
     }

定义认证规则
定义了3个角色

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
                  .withUser("root").password("123").roles("ADMIN","DBA")
                  .and()
                  .withUser("admin").password("123").roles("ADMIN","USER")
                  .and()
                  .withUser("zhou").password("123").roles("USER");
    }
**

/**
* 定义授权规则
* http.authorizeRequests() 开启HttpSecurity的配置
* permitAll() 不需要认证就可访问
* anyRequest().authenticated(),除使用antMatchers已定义的URL外,其它全部需要认证
* formLogin()
* 没有使用loginPage自定义页面时(路径!!!), 默认使用security的login页面
*
* 默认使用登陆参数名:username,password
*.csrf().disable()不能省略,否则会重定向回login页面
注:自定义登录页面时中action的URL需要跟配置类中的loginPage的URL一致
*/

  @Override
     protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/index/**").permitAll()
                  .antMatchers("/admin/**").hasRole("ADMIN")
                  .antMatchers("/root/**").access("hasRole('ADMIN') and hasRole('USER')")
                  .antMatchers("/dba/**").hasRole("DBA")
                  .antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')")
                  .anyRequest().authenticated();
                  http.formLogin().usernameParameter("username")
                          .passwordParameter("password")
                          .loginProcessingUrl("/login")
                  /**
                   * 验证成功
                   *  登陆成功的用户信息
                   * auth.getPrincipal();
                   */
                   .successHandler(new AuthenticationSuccessHandler() {
                       @Override
                       public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                           Object principal = auth.getPrincipal();
                           resp.setContentType("application/json;charset=utf-8");
                           PrintWriter out = resp.getWriter();
                           resp.setStatus(200);
                           Map<String,Object> map=new HashMap<>();
                           map.put("status",200);
                           map.put("msg",principal);
                           //jackJSon
                           ObjectMapper om=new ObjectMapper();
                           out.write(om.writeValueAsString(map));
                           out.flush();
                           out.close();
                       }
                   })
                  .failureHandler(new AuthenticationFailureHandler() {
                      @Override
                      public void onAuthenticationFailure(HttpServletRequest req,
                                                          HttpServletResponse resp,
                                                            AuthenticationException e) throws IOException, ServletException {
                          resp.setContentType("application/json;charset=utf-8");
                          PrintWriter out = resp.getWriter();
                          resp.setStatus(401);
                          Map<String,Object> map=new HashMap<>();
                          map.put("status",401);
                          if(e instanceof LockedException){
                           map.put("msg","账户被锁定,登录失败!");
                          }else if(e instanceof BadCredentialsException){
                              map.put("msg","账户名或密码输入错误,登录失败!");
                          }else if(e instanceof DisabledException){
                              map.put("msg","账户被禁用,登录失败!");
                          }else if(e instanceof AccountExpiredException){
                              map.put("msg","账号已过期,登录失败!");
                          }else if(e instanceof CredentialsExpiredException){
                              map.put("msg","密码已过期,登录失败!");
                          }else{
                              map.put("msg","登录失败!");
                          }
                          ObjectMapper om=new ObjectMapper();
                          out.write(om.writeValueAsString(map));
                          out.flush();
                          out.close();
                      }
                  })
                   .permitAll()
                          .and()
                          .logout().logoutSuccessUrl("/login_page")
                   .and().csrf().disable();
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值