初识Spring Security

  • 内容
  • 相关

Spring Security入门


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/>
    </parent>


引入依赖:


<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>


写一个测试:



@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("demo")
    public String demo(){
        return "demo";
    }

启动项目并访问。



默认:user
密码:控制台随机生成


登录后



基本原理:SpringSecurity本质是一个过滤器链

简单使用:

SecurityConfig:



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    public PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }
}


MyUserDetailsService:


public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private MyUserService myUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        MyUser one = myUserService.lambdaQuery().eq(MyUser::getStudentName, s).one();
        if(ObjectUtil.isNull(one)){
            throw new UsernameNotFoundException("用户不存在!");
        }
        List<GrantedAuthority> oath= AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //从数据返回对象,得到用户名和密码
        return new User(one.getUserName(),new BCryptPasswordEncoder().encode(one.getPassword()),oath);
    }
}

即可通过查询数据库进行登录验证。



本文标签:

版权声明:若无特殊注明,本文皆为《z》原创,转载请保留文章出处。

本文链接:初识Spring Security - https://www.52zzk.cn/post-142.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注