1.实现UserDetailService与自定义逻辑
自定义用户类需要实现UserDetails接口,并实现接口的方法,所以我们编写下述代码。
package com.yzxb.SpringSecurity.service; import com.yzxb.SpringSecurity.pojo.Role; import com.yzxb.SpringSecurity.pojo.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.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Service public class MyUserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 1-本地mysql用户存在性查询 User user = selectUserFromDb(); if (Objects.isNull(user)) { throw new UsernameNotFoundException("用户不存在"); } // 2-本地查询权限 List<Role> roles = selectAuthFromDb(); // 3-设置权限信息 user.setRoles(roles); // 4-返回权限合集 return user; } /** * TODO 如果需要调用数据库查询,这里接入orm持久层框架即可 * @return 用户本地权限合集 */ private List<Role> selectAuthFromDb() { return new ArrayList<>(); } /** * TODO 如果需要调用数据库查询,这里接入orm持久层框架即可 * @return 本地用户信息 */ private User selectUserFromDb() { return new User(); } }
2.注册自定义实现类
package com.yzxb.SpringSecurity.config; import com.yzxb.SpringSecurity.service.MyUserService; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import javax.annotation.Resource; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Resource private MyUserService myUserService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and().formLogin().loginPage("/login.html") .loginProcessingUrl("/doLogin") .defaultSuccessUrl("/demo/index ") .failureUrl("/login.html") .usernameParameter("uname") .passwordParameter("passwd") .permitAll() .and() .csrf() .disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(myUserService); } }
改完的效果如下图
然后重启项目,就可以实现自定义的数据库认证逻辑。