[spring security笔记]2.0,web权限方案--用户认证

16 篇文章 0 订阅

#配置文件方式

server:
  port: 8011
spring:
  security:
    user:
      name: admin
      password: 123
@RestController
public class helloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }
}

#编写类实现接口

 @Configuration
public class securityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth可以设置用户名和密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();//加密
        String encode = bCryptPasswordEncoder.encode("123456");
        auth.inMemoryAuthentication().withUser("root").password(encode).roles("admin");
    }
    @Bean //注册编码器,不注册会报错
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

 

 #自定义实现类

@Service("userDetailsService") //当前对象注入容器时的名称
public class myUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User("boy",new BCryptPasswordEncoder().encode("123"),auths);
    }
}
@Configuration
public class securityConfig1 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());//填入自定义的实现类
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

 #查询数据库完成认证

 

@SpringBootApplication
@MapperScan("com.malred.security.mappers")
public class SecuritySggApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecuritySggApplication.class, args);
    }
}
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver #boot2.2开始,默认支持mysql8,需要加上cj
    username: root
    password: 
    url: jdbc:mysql://localhost:5408/demo

@Repository
public interface userMapper extends BaseMapper<user> {
}

@Repository
public interface userMapper extends BaseMapper<user> {
}
@Data
@TableName("columns") //表名为columns
public class user {
    private String username;
    private String password;
    private Integer id;
}
@Service("userDetailsService") //当前对象注入容器时的名称
public class myUserDetailsService implements UserDetailsService {
    @Autowired
    private com.malred.security.mappers.userMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名来查询数据库
        QueryWrapper<user> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        user user = userMapper.selectOne(wrapper);
        //判断是否存在
        if(user==null) throw new UsernameNotFoundException("用户名不存在");//抛出异常
        //权限集合
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //返回一个认证成功的用户信息
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

 

#自定义登录页面

修改配置类 

@Configuration
public class securityConfig1 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());//填入自定义的实现类
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义登录页面
                .loginPage("/login.html") //跳转到自己的登录页面,只能是接口
                .loginProcessingUrl("/user/login")  //登录访问路径(表单提交到哪个controller),security会自动处理
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后跳转到哪
                .and().authorizeRequests() //哪些需要认证才能访问,哪些不需要
                .antMatchers( "/user/login", "/hello").permitAll() //访问这些路径的时候不需要认证
                .anyRequest().authenticated() //表示其他所有请求都需要认证
                .and().csrf().disable(); //关闭csrf的认知防护
    }
}

写需要的页面

<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>你好,这是首页</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
    <!--必须叫username和password,否则security不能识别 -->
    用户名: <input type="text" name="username"> <br>
    密码: <input type="text" name="password"> <br>
    <input type="submit" value="login">
</form>
</body>
</html>

接口


@Controller
@RequestMapping("/test")
public class testController {
    @RequestMapping("/index")
    public String login(){
        return "index";
    }
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鸟malred

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值