原文链接:http://www.jylt.cc/#/detail?id=f195809b0df82e5197896982fa3565f1
认证
实现认证功能
认证功能需实现UserDetailsService
接口
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private UserMapper userMapper;
@Override
public User loadUserByUsername(String username) throws UsernameNotFoundException {
if (StringUtils.isEmpty(username)) {
throw new UsernameNotFoundException("用户名不能为空!");
}
SysUser user = userMapper.selectByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户名或密码错误!");
}
return new User(user.getAccount(), user.getPassword(), AuthorityUtils.createAuthorityList("edit,edit_or_update,ROLE_admin"));
}
}
说明:其中的重写的方法
loadUserByUsername(String username)
是认证的逻辑。
在返回的User
对象中,第三个参数是定义用户的权限和角色。
注意:
- 定义用户角色的时候必须以
ROLE_
开头,比如ROLE_admin
就定义了admin的角色。
而前面的edit
和edit_or_update
是用户的权限。
记住我
在SecurityConfig.class
中加入以下配置:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private DataSource dataSource;
@Bean
public PersistentTokenRepository jdbcTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
// 启动时是否创建记住我的配置表,首次启动可以开启,以后再启动需要关闭
// jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
// 设置记住我功能
httpSecurity.rememberMe()
// 设置前端给的记住我参数,值为boolean值,为true时记住我
.rememberMeParameter("rememberMe")
// 配置token仓库
.tokenRepository(jdbcTokenRepository())
// 设置多长时间内记住我,默认是两周
.tokenValiditySeconds(10080);
.userDetailsService(userDetailsService)
httpSecurity.csrf().disable();
}
注意:
- 如果登陆的时候返回的是自定义的
UserDetails
的实现类,一定要注意重写的方法String getUsername()
返回值,这个值就是记住我存在数据库中username
字段的值。 userDetailsService()
方法一定要设置,需要通过这个方法来进行登录验证。
退出登录
在SecurityConfig.class
中加入以下配置:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {\
// 退出登录配置
httpSecurity.logout()
// 退出登录时请求的接口地址
.logoutUrl("/user/login_out")
// 退出登录成功后的处理器
.logoutSuccessHandler()
// 退出登录成功后跳转的url
.logoutSuccessUrl();
httpSecurity.csrf().disable();
}
}
具体代码实现可参考:https://gitee.com/gitwcx/walter-blog.git-> auth
模块