1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
2.添加配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 密码加密策略
* @return
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception{
super.configure(web);
}
@Override
public void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
//.antMatchers("/user/findAll").hasRole("admin")//访问接口需要admin角色
.antMatchers("/stock").permitAll()//测试redis lock
.antMatchers("/css/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/plugins/**").permitAll()
.antMatchers("/admin/**").access("@authService.auth(request,authentication)")//访问该接口需要通过认证服务
.antMatchers("/pages/**").authenticated()//认证成功就可以通过
.and().formLogin()
.loginPage("/login.html")//自定义的登录页面
.loginProcessingUrl("/login")//登录处理接口
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/pages/main.html")
.failureUrl("/login.html")
.permitAll()//通过 不拦截 指登录表单相关的接口都通过
.and().logout()//退出登录配置
.logoutUrl("/logout")//退出登录接口
.logoutSuccessUrl("/login.html")
.permitAll()
.and()
//.httpBasic()//单纯的http访问也会拦截 如postman
//.and()
.csrf().disable()//csrf关闭 如果自定义登录 需要关闭
.headers().frameOptions().sameOrigin();//支持iframe页面嵌套
}
}
3.登录认证功能
@Component
public class SecurityUserService implements UserDetailsService {
@Autowired
private AdminService adminService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//登录的时候会把username传递到这里
//通过username查询admin表,如果存在,将密码告诉spring security
//如果不存在,返回null,认证失败
Admin admin = adminService.findAdminByUsername(username);
if(admin == null){
//登录失败
return null;
}
UserDetails userDetails = new User(username,admin.getPassword(),new ArrayList<>());
return userDetails;
}
}
4.权限授权功能
@Service("authService")
public class AuthService {
@Autowired
private AdminService adminService;
public boolean auth(HttpServletRequest request, Authentication authentication){
//比较当前登录用户所拥有的请求接口是否等于当前请求路径
String url = request.getRequestURI();
Object principal = authentication.getPrincipal();
if(principal ==null || "anonmousUser".equals(principal)){
//未登录
return false;
}
UserDetails userDetails = (UserDetails) principal;
String username = userDetails.getUsername();
Admin admin = adminService.findAdminByUsername(username);
if(admin==null){
return false;
}
//超级管理员
if(1==admin.getId()){
return true;
}
Long id = admin.getId();
List<Permission> permissionList = adminService.findPermissionByAdminId(id);
url = StringUtils.split(url,'?')[0];
for (Permission permission : permissionList) {
if(url.equals(permission.getPath())){
return true;
}
}
//todo 添加角色,用户拥有多个角色,每个角色拥有多个权限
return false;
}
}