SpringSecurity
实现用户认证和用户授权,访问合法等功能的一个安全框架。ps:shiro国内市场占有率比这个高。
需求
springboot+security实现用户认证和授权
编码
第一步: 编写Config类 注意@注解的引入
@EnableWebSecurity
public class SecurConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/*").hasRole("VIP1")
.antMatchers("/level2/*").hasRole("VIP2")
.antMatchers("/level3/*").hasRole("VIP3")
.and()
.formLogin()
.loginPage("/userlogin")
.and()
.logout()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
//根据用户名查询数据库实现认证,SecurityUser继承UserBean和实现UserDetails接口为了授权。
@Bean
protected UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Autowired
UserRepository up;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = up.findByUsername(username);
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
if(user==null)throw new UsernameNotFoundException("Username " + username + " not found");
return new SecurityUser(user);
}
};
}
}
第二步:编写User类
public class SecurityUser extends User implements UserDetails{
public SecurityUser(User user) {
// TODO Auto-generated constructor stub
this.setId(user.getId());
this.setPassword(user.getPassword());
this.setUsername(user.getUsername());
this.setRole(user.getRole());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
String username = this.getUsername();
if(StringUtils.hasText(username)) {
SimpleGrantedAuthority authority=new SimpleGrantedAuthority(this.getRole());
authorities.add(authority);
}
return authorities;
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}