Spring Security(1)简单使用

209 阅读1分钟

jar包

这里是配合spring boot环境下的使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

security配置

需要一个继承WebSecurityConfigurerAdapter的配置类,这里定其名为SecurityConfig

    // 这里是配置不需要过滤器的url
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/hello/test");
    }
    
    // 基本配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable().csrf().disable();
        http.authorizeRequests().anyRequest().authenticated()
                //登出
                .and().logout()
                .permitAll() // 允许所有用户
                .logoutSuccessHandler(this::logoutHandler)// 登出成功处理逻辑
                .and().formLogin()
                .permitAll()//允许所有用户
                .successHandler(this::loginSuccessHandler)//登录成功处理逻辑
                .failureHandler(this::loginFailureHandler)//登录失败处理逻辑
                //异常处理(权限拒绝、登录失效等)
                .and().exceptionHandling()
                .accessDeniedHandler(this::accessDeniedHandler) // AccessDeniedException处理逻辑,用户自定义的方法
                .authenticationEntryPoint(this::authenticationEntryPoint) // AuthenticationException处理逻辑,用户自定义的方法
                //会话管理
                .and().sessionManagement()
                .maximumSessions(1);//同一账号同时登录最大用户数;
        http.addFilterBefore(securityInterceptor, FilterSecurityInterceptor.class);
    }

过滤器

这里定过滤器的名字为SecurityFilter

    @Override
    // 在这个过滤器里可以做验证token、验证权限等事情
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        UserDetails userDetails = customUserDetailsService.loadUserByUsername("1");
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // 将用户的信息放在当前线程中,便于后面的使用,注意这里是必须的
        SecurityContextHolder.getContext()
                .setAuthentication(authentication);

        filterChain.doFilter(request,response);
    }

身份信息

需要一个实现UserDetailsService接口的类

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = new User("userName", "password", new ArrayList());
        return user;
    }

这里的User类记载用户的信息,包含姓名,密码,权限等,可以自己写一个类实现UserDetails接口返回,赋予用户不同的信息