在配置类中实现Spring Security,主要是在继承了WebSecurityConfigurerAdapter的配置中,重写WebSecurityConfigurerAdapter的三个Configure方法:
1、configure(AuthenticationManagerBuilder auth)--进行用户的认证
2、configure(HttpSecurity http)--对请求的资源访问权限限定
3、configure(WebSecurity web)--配置Spring Security的filter链
对于Spring Security中用户认证,我使用三种方式演示:
**方式1、**基于内存的用户认证,在configure(AuthenticationManagerBuilder auth)方法中作如下配置:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("fox").password("123456").roles("ADMIN").and() //在roles()方法所给定的值都会添加一个前缀ROLE_
.withUser("nov").password("123456").roles("ADMIN","BOSS");
}
启动项目,在Spring Security的默认登录页面就可以登录成功了,进入index页面。
**方式2**、基于数据库的认证
基于数据库认证,就是通过查询数据库数据,进行用户认证,在实际开发中可以根据自己的需求选择。
第一步:配置数据源--DataSource
第二步:重写configure(AuthenticationManagerBuilder auth),配置数据源
@Autowired
private DataSource dataSource;
...............
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*auth
.inMemoryAuthentication()
.withUser("fox").password("123456").roles("ADMIN").and() //在roles()方法所给定的值都会添加一个ROLE_
.withUser("nov").password("123456").roles("ADMIN","BOSS");*/
//usersByUsernameQuery中的True字段是用来判断账号是否有效的,因为没有这个字段,所以直接设置为true,##注意字段的别名##
String usersByUsernameQuery = "select user.u_name username , `user`.u_password password , true from user where `user`.u_name = ?";
String authorities = "SELECT user.u_name username ,role.r_name ROLE_USER "
+ "FROM `user_role`, USER, role "
+ "WHERE USER .u_name = ? AND `user`.id = user_role.user_id and user_role.role_id = role.id";
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(usersByUsernameQuery)
.authoritiesByUsernameQuery(authorities);
}
如上所示,就配置完成基于数据库的配置。可以再次启动项目,访问index页面,输入存储于数据库的用户进行认证。
**方式3**、配置自定义的用户服务【强推】
实现自定义用户服务需要实现接口import org.springframework.security.core.userdetails.UserDetailsService;重写方法public UserDetails loadUserByUsername(String username),在这个方法里面完成根据用户名查询用户的操作。
①自定义MyUserDetailsService
public class MyUserDetailsService implements UserDetailsService{
//没有在spring的应用上下文注册,不能使用@AutoWired
private UserMapper mapper;
public MyUserDetailsService(UserMapper mapper) {
this.mapper = mapper;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//MyUserDetails 是实现了接口UserDetails的对象,用来存储根据前台输入用户名查出来的用户信息
MyUserDetails userDetails = null ;
//根据用户名查找用户信息,这样可以将用户对象存储在任何地方了
User user = mapper.findUserByUsername(username);
if(user != null && !StringUtils.isEmpty(user.getId())){
List<Role> roles = mapper.queryRoleByUid(user.getId());
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority(role.getrName()));
}
userDetails = new MyUserDetails(user.getuName(), user.getuPassword(), list, user.getId());
return userDetails;
}
throw new UsernameNotFoundException(" User: "+username+" not found ");
}
}
②自定义的MyUserDetails
public class MyUserDetails implements UserDetails{
private static final long serialVersionUID = -5896459318065548072L;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
private String uid;
public MyUserDetails() {}
public MyUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities, String uid) {
super();
this.username = username;
this.password = password;
this.authorities = authorities;
this.setUid(uid);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return this.authorities;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return this.password;
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return this.username;
}
@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;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
③修改configure(AuthenticationManagerBuilder auth)
auth
.userDetailsService(new MyUserDetailsService(mapper));
如此,重启项目,再次访问index页面,进行验证即可