栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合SpringSecurity的三种方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合SpringSecurity的三种方式

导入依赖


     org.springframework.boot
     spring-boot-starter-security
 



     org.springframework.security
     spring-security-test
     test

     

方式一:在application.properties中配置

server.port= 8080
spring.security.user.name= xxx
spring.security.user.password=xxx

方式二:通过配置类

//第二种实现方式
public class myTwoSecurity extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123");
        
        auth.inMemoryAuthentication().withUser("lok").password(encode).roles("admin");
    }
    @Bean
    public PasswordEncoder password(){ return  new BCryptPasswordEncoder();}
}

方式三:自定义配置类 模拟从数据库查询数据

1、编写配置类

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

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }
    @Bean
    public PasswordEncoder password(){ return  new BCryptPasswordEncoder();}
}

2、编写Service

@Service("userDetailsService")
//注意@Service("userDetailsService") 的名字 要与1中private UserDetailsService userDetailsService;的相同

public class MyUser implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        List authorities= AuthorityUtils.commaSeparatedStringToAuthorityList("roole");
        
        System.out.println("走到这里");
        return new User("xiaokai",new BCryptPasswordEncoder().encode("123"),authorities);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号