SpringSecurity的简单应用
角色权限授权
可根据需求,自定义过滤器,并放到过滤器链中
自定义一个配置SecurityConfig
/**
* 流程:
* 配置config :配置过滤器,自定义认证(设置重写的用来查询用户信息的UserDetailsService) -> {
* 过滤器:-> {
* 根据请求封装自定义授权信息 xxxAuthentication
* }
* 自定义认证:拿到 xxxAuthentication ->{
* 1.根据xxxAuthentication里头的信息,做自定义认证
* 2.交给重写loadUserByUsername的UserDetailsService处理:做用户信息、权限的获取,并保存
* 3.校验成功用户信息及权限封装至xxxAuthentication
* }
* }
*
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private StudentDetailsService studentDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
StudentFilter studentFilter = new StudentFilter();
studentFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
StudentAuthenticationProvider studentAuthenticationProvider = new StudentAuthenticationProvider();
studentAuthenticationProvider.setUserDetailsService(studentDetailsService);
http.authenticationProvider(studentAuthenticationProvider).addFilterAfter(studentFilter, UsernamePasswordAuthenticationFilter.class);
}
}
xxxDetailService
@Service
public class StudentDetailsService implements UserDetailsService {
@Resource
private StudentService studentService;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Student one = studentService.lambdaQuery().eq(Student::getStudentName, s).one();
if(ObjectUtil.isNull(one)){
throw new UsernameNotFoundException("用户不存在!");
}
Student student = new Student();
//权限集合
Set<GrantedAuthority> authorities = new HashSet<>();
BeanUtils.copyProperties(one,student);
//找出角色
List<SysRole> roleByUserId = studentService.findRoleByUserId(one.getStudentId());
roleByUserId.forEach(role->{
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
});
//找出权限
List<SysAuth> authByUserId = studentService.findAuthByUserId(one.getStudentId());
authByUserId.forEach(sysAuth -> {
authorities.add(new SimpleGrantedAuthority(sysAuth.getName()));
});
student.setAuthorities(authorities);
return student;
}
}
Provider
@Component
public class StudentAuthenticationProvider implements AuthenticationProvider {
/**
* 在spring security中存放用户信息的类
*/
private UserDetailsService userDetailsService;
/**
* 具体的认证方法-认证存在studentToken里的信息
* @param authentication
* @return
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
StudentToken studentToken = (StudentToken) authentication;
//自定义认证
//todo
String username = (String) authentication.getPrincipal();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
StudentToken studentAuth = new StudentToken(userDetails.getAuthorities(), userDetails, null);
studentAuth.setDetails(studentToken.getDetails());
return studentAuth;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public boolean supports(Class<?> aClass) {
return false;
}
}
protected void configure(HttpSecurity http) throws Exception {
// 转成数组
String[] passMatcher = JWTConfig.antMatchers.toArray(new String[JWTConfig.antMatchers.size()]);
http.apply(securityConfig).and()
.authorizeRequests()
// 如果有允许匿名的url,填在下面 就是不用登录
.antMatchers(passMatcher).permitAll()
// 用户登录以后可以访问
.anyRequest().authenticated()
.and()
// 设置登陆url
.logout().logoutUrl("/user/logout").permitAll()
.and()
// 禁用session 全部使用token
.sessionManagement().disable()
// 禁用csrf
.csrf().disable();
// 禁用缓存
http.headers().cacheControl();
http.addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), LogoutFilter.class);
http.exceptionHandling().accessDeniedHandler(new CustomNoAccessDeniedEntryPoint()).authenticationEntryPoint(new CustomAuthenticationEntryPoint());
}