Spring Security入门四:自定义登录校验逻辑

十年热恋 提交于 2020-12-27 00:53:49

在《Spring Security入门三:配置自定义登录页面》一文中,我配置了自定义的登录页面来替代Spring Security提供的默认页面。但是校验处理还是Spring Security的默认处理,我们只能使用user及后台随机产生的密码来登录,这无法满足实际的业务需求。我们想要使用自己的规则来进行用户登录校验,要如何作呢?

Spring Security中提供了一个用户登录校验接口UserDetailsService,我们可以实现这个接口,并将实现类声明为@Service,系统将自动用我们自定义的这个实现替换掉默认的校验。我使用org.springframework.security.crypto.bcrypt包里的BCryptPasswordEncoder来实现密码的加解密。这里需要在配置类中实现@bean方法来创建一个BCryptPasswordEncoder的实例, 下面是我的代码实现:

1.先在LoginConfig配置类里添加如下代码:

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

2.然后创建UserDetailService的实现类UserDetailServiceImpl并实现loadUserByUsername这个校验方法:

package com.efsoft.springsecuritydemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    //注入密码处理器

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("开始登录效验...");
        //1.检查用户
        //这个例子指定用户名为admin.应该用数据库判断用户是否存在
        if (!"admin".equals(s)) {
            throw new UsernameNotFoundException("用户名不存在。");
        }
        //模拟产生一个密码123
        //实际业务逻辑应该从数据库中提取
        String password = passwordEncoder.encode("123");

        //执行校验,User实例在创建时会执行校验处理,如果校验没通过则会抛出异常。
        return new User(s, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
    }
}
在本例中,我将用户名修改为admin,密码修改为123.再次运行本例来看看效果。首先看下后台,系统不再产生随机密码了,然后在浏览器访问127.0.0.1:8080,输入用户名admin,密码123,也可以成功登录了。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!