1.默认身份验证
在pom.xml文件映入SpringSecutrity依赖启动器,启动项目,访问文章列表页面时,出现默认的登录页,需要用默认用户名:user,密码源于控制台输出,也就是最基础的登录
自定义用户名和密码(用户名和密码是写在代码内,不好维护),新建
/*开启安全管理配置*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*自定义身份认证*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*密码编译器*/
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/*1.基于内存的身份认证*/
//添加两个账户密码
auth.inMemoryAuthentication().passwordEncoder(encoder)
.withUser("admin").password(encoder.encode("admin")).roles("admin")
.and()
.withUser("junko").password(encoder.encode("123456")).roles("common");
}
}
启动项目,需要输入上面定义好的账户密码才能进行登录,这里有三张表,分别为用户、权限、用户-权限表
@Mapper
public interface TUserMapper {
/*根据用户名去查询用户讯息*/
@Select("select * from t_user where username=#{username}")
public TUser selectUserByUserName(String username);
}
@Mapper
public interface AuthorityMapper {
/*根据用户名去查询用户权限*/
public List<Authority> selectAuthorityByUserName(String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.junko.mapper.AuthorityMapper">
<select id="selectAuthorityByUserName" resultType="net.junko.bean.Authority" parameterType="string">
select a.* from t_user u,t_authority a,user_authority au where u.id=au.uid and a.id=au.aid and u.username=#{username}
</select>
</mapper>
前面说过,使用数据库的查询方法进行授权认证,需要实现UserDetailsService接口,重写loadUserByUsername方法
@Service
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
TUserMapper userMapper;
@Autowired
AuthorityMapper authorityMapper;
/*根据前端登录页面传入的用户名,查询出数据库对应的用户信息和用户权限,
把用户信息和权限封装成UserDetails对象,交给SpringSecurity进行身份认证*/
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/*根据用户名查询用户信息、权限信息*/
TUser user = userMapper.selectUserByUserName(s);
List<Authority> authorities = authorityMapper.selectAuthorityByUserName(s);
/*遍历封装用户权限*/
List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
for (int i=0;i<authorities.size();i++)
{
authorityList.add(new SimpleGrantedAuthority(authorities.get(i).getAuthority()));
}
if(user!=null)
{
/*将用户名、密码、用户权限封装成UserDetails对象*/
UserDetails userDetails = new User(user.getUsername(),encoder.encode(user.getPassword()),authorityList);
return userDetails;
}
else {
throw new UsernameNotFoundException("用户不存在");
}
}
}
之前2的内存身份验证记得注释掉,注入UserDetailsServiceImpl
/*开启安全管理配置*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
/*自定义身份认证*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*密码编译器*/
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/*1.基于内存的身份认证*/
// auth.inMemoryAuthentication().passwordEncoder(encoder)
// .withUser("admin").password(encoder.encode("admin")).roles("admin")
// .and()
// .withUser("cai").password(encoder.encode("123457")).roles("common");
/*2.使用UserDetails进行身份认证*/
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
}
测试,登录时用数据库内存储的用户信息
在做好了认证方式后,想要指定不同的权限访问不同的页面,即自定义访问控制,则需要再进行一些设置
/*开启安全管理配置*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
/*自定义身份认证*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*密码编译器*/
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/*1.基于内存的身份认证*/
// auth.inMemoryAuthentication().passwordEncoder(encoder)
// .withUser("admin").password(encoder.encode("admin")).roles("admin")
// .and()
// .withUser("cai").password(encoder.encode("123457")).roles("common");
/*2.使用UserDetails进行身份认证*/
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
/*自定义用户权限*/
@Override
protected void configure(HttpSecurity http) throws Exception {
/*自定义访问控制*/
http.authorizeRequests()
.antMatchers("/").permitAll() //表示放行“/”访问
//根据用户拥有的不同权限配置访问权限
.antMatchers("/admin/**").hasAuthority("admin")
.antMatchers("/common/**").hasAuthority("common")
.and()
.formLogin();
}
}
在自定义用户权限设置后,就可以实现 / 路径下的页面不需要认证即可访问, /admin/** 下的页面,则需要登录的用户具有admin权限才能访问,同理 /common/**
来源:https://www.tuicool.com/articles/rAr6nez