Spring Security: 自定义用户名密码认证

需求

  1. 实现多用户访问
  2. 从指定数据源中检索用户数据。
  3. 使用自定义的登陆页面。

思路

Spring Security : 用户名密码认证中的时序图可以发现:Spring Security已经实现了完整的用户名密码认证的逻辑。因此只要DaoAuthenticationProvider#retrieveUser()方法返回的UserDetails实例是从指定数据源中检索到的,那么就可以实现“从指定数据源检索用户数据”的需求。当“指定数据源”中的存在多个用户时,同时会实现“多用户访问”。

实现

模型

自定义用户对象 MyUser

org.springframework.security.core.userdetails.User 是Spring Security已实现的UserDetails实现。继承该类。

public class MyUser extends User {

    public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    public MyUser(String username,
            String password,
            boolean enabled,
            boolean accountNonExpired,
            boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
}

数据源

模拟数据源 RepositoryUtils

模拟数据源,数据源中保存用户及权限信息

public class RepositoryUtils {
    static List<MyUser> users = new ArrayList<>();
    static {
        //密码加密工具
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(4);

        //创建用户并设置用户角色
        ArrayList<SimpleGrantedAuthority> userAuth = new ArrayList<>();
        userAuth.add(new SimpleGrantedAuthority("MEMBER"));
        users.add(new MyUser("user", passwordEncoder.encode("123"), userAuth));

        ArrayList<SimpleGrantedAuthority> merchantAuth = new ArrayList<>();
        merchantAuth.add(new SimpleGrantedAuthority("MERCHANT"));
        users.add(new MyUser("merchant", passwordEncoder.encode("123"), merchantAuth));

        ArrayList<SimpleGrantedAuthority> adminAuth = new ArrayList<>();
        adminAuth.add(new SimpleGrantedAuthority("ADMIN"));
        users.add(new MyUser("admin", passwordEncoder.encode("123"), adminAuth));

    }

    static MyUser findUserByUsername(String username) {
        for (MyUser user : users) {
            if(StringUtils.equals(username, user.getUsername()))
                return user;
        }
        throw new UsernameNotFoundException(username);
    }
}

数据源访问

从数据源中检索UserDetails。

@Component
public class UserRepository {
    public MyUser findUserByUsername(String username) {
        return RepositoryUtils.findUserByUsername(username);
    }
}

自定义UserDetailsService实现

从指定数据源检索UserDetails。实现UserDetailsService接口。

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    /**
     * 根据用户名从数据源中检索用户信息
     *
     * @param username
     *
     * @return
     *
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username))
            throw new IllegalArgumentException("username is empty");

        return userRepository.findUserByUsername(username);
    }
}

登陆页面

自定义登陆页面

resources目录下新增templates目录,新增文件login.html

<form th:action="@{/login}" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>

配置View

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}

访问资源

模拟用户访问需要认证的资源。

@RestController
public class HelloEndpoint {
    @GetMapping("/")
    public String hello() {
        return "hello, Spring Security";
    }
}

配置Spring Security 用户名密码认证

继承WebSecurityConfigurerAdapter。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()/*设置认证请求URL*/
                .antMatchers(HttpMethod.GET,"/home", "/login", "/login.html").permitAll()/*设置无需认证的URL*/
                .anyRequest().authenticated()/*任何URL都需要认证*/

                .and()/* 完成上一个配置,进行下一步配置 */

                .formLogin()/* 配置表单登录 */
                .usernameParameter("username") /* 默认值 username */
                .passwordParameter("password") /* 默认值 password */
                .loginPage("/login") /* 设置登录页面,默认是HTTP GET /login */
                .loginProcessingUrl("/login") /* 设置登录页面,默认是HTTP POST /login */

                .and()/* 完成上一个配置,进行下一步配置 */

                .logout()/* 配置表单登录 */
                .logoutSuccessUrl("/home");/* 设置退出页面 */
    }

    /**
     * spring5.0之后,spring security必须设置加密方法否则会报
     * There is no PasswordEncoder mapped for the id "null"
     *
     * @return 加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(4);
    }

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

测试

  1. 启动后的访问地址:http://localhost:8080/

Spring Security: 自定义用户名密码认证

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值