时间:2021-07-01 10:21:17 帮助过:17人阅读
1、加入spring security的支持包,
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2、主要实现两个接口,一个是UserDetails 用户详细信息,一个是UserDetailsService用户信息服务
public class AuthorityUser implements UserDetails { private NewUser user; public AuthorityUser(NewUser newUser) { this.user = newUser; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<NewAuthority> newAuthorities = user.getNewAuthorities(); if(user == null || newAuthorities.size() <1){ return AuthorityUtils.commaSeparatedStringToAuthorityList(""); } StringBuilder commaBuilder = new StringBuilder(); for(NewAuthority authority : newAuthorities){ commaBuilder.append(authority.getName()).append(","); } String authorities = commaBuilder.substring(0,commaBuilder.length()-1); return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities); } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return user.getEnable().equals(1)?true:false; } }
public class SpringDataUserDetailsService implements UserDetailsService {
@Autowired
NewUserMapper newUserMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
NewUser user = newUserMapper.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("username:" + username + " not found");
}
return new AuthorityUser(user);
}
}
3、在继承WebSecurityConfigurerAdapter 子类中添加资源拦截规则和 用户权限规则
@EnableWebSecurity public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //自定义权限规则 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasAuthority("VIP1") .antMatchers("/level2/**").hasAuthority("VIP2") .antMatchers("/level3/**").hasAuthority("VIP3"); //开启自动配置的登陆功能 http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin"); //开启自动配置注销 http.logout().logoutSuccessUrl("/");//注销成功来到首页 http.rememberMe().rememberMeParameter("remenber");//开启记住我功能 } //定义认证规则 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//设置自定义UserDetailService,用以从数据库加载用户信息 auth.userDetailsService(springDataUserDetailsService()) //设置密码加密 .passwordEncoder(new MyPasswordEncoder()); } @Bean public SpringDataUserDetailsService springDataUserDetailsService() { return new SpringDataUserDetailsService(); }
springboot 使用数据库用户权限登录
标签:首页 boolean throw extend word vip remember ant group