SpringSecurity的简单应用

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());
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值