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

SpringSecurity实现简单的用户认证

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

SpringSecurity实现简单的用户认证

引入SpringSecurity的依赖:


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


然后启动项目,会发现项目已被SpringSecurity接管,进入任何页面之前都要登录,下面是SpringSecurity的默认登录页:

在后端会有一个随机密码生成,使用user用户登录就可以进入其他页面。

为了实现自定义用户名密码的认证,可以通过在application.properties中添加属性spring.security.user.name和spring.security.user.password来实现,也可以通过代码实现。代码的实现方式是继承WebSecurityConfigurerAdapter类(注意不要忘了@Configuration注解),覆写其中的configure(AuthenticationManagerBuilder auth)方法:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String encode = new BCryptPasswordEncoder().encode("123456");
auth.inMemoryAuthentication().withUser("root").password(encode).roles("root");
    }

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

密码一般都要加密,加密方式必须使用@Bean注解,否则会报错There is no PasswordEncoder mapped for the id "null"。

正常业务的用户名和密码需要查询数据库,这是需要使用UserDetailsService接口。编写一个类实现该接口,然后返回UserDetails类型的对象:

@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List list = AuthorityUtils.commaSeparatedStringToAuthorityList("root");
        return new User("root", new BCryptPasswordEncoder().encode("123456"), list);
    }
}

这里为了简便,没有查询数据库,而是将用户名密码以及权限在程序中写死,后期会链接数据库。而刚才的configure(AuthenticationManagerBuilder auth)方法中的内容为:

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

其中的userDetailsService为Spring自动注入的私有属性。以上就是实现权限认证的三种方式。

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

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

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