springsecurity配置类以及授权逻辑的编写

简介: springsecurity配置类以及授权逻辑的编写

 项目结构

 

image.gif编辑

Security配置类

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)// 开启鉴权配置注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //解决跨域
    CorsConfigurationSource configurationSource() {
        List list=new ArrayList();
        list.add("http://127.0.0.1:80/");
        list.add("http://127.0.0.1:81/");
        list.add("http://127.0.0.1:82/");
        list.add("http://127.0.0.1:83/");
        list.add("http://127.0.0.1:84/");
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        //允许跨域访问的请求方式Arrays.asList("GET","POST")
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        //允许跨域访问的站点Arrays.asList("http://127.0.0.1:5173/")Collections.singletonList("*")
        corsConfiguration.setAllowedOrigins(list);
        // 允许携带凭证
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //对所有URL生效
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义表单登录
        http.formLogin()
                .usernameParameter("username") // 用户名项
                .passwordParameter("password") // 密码项
                .loginProcessingUrl("/admin/login") // 登录提交路径
                .successHandler(new MyLoginSuccessHandler()) // 登录成功处理器
                .failureHandler(new MyLoginFailureHandler()) // 登录失败处理器
                // 跨域配置
                .and()
                .cors()
                .configurationSource(configurationSource());
        // 权限拦截配置
        http.authorizeRequests()
                //.antMatchers("/login").permitAll() // 登录页不需要认证
                .antMatchers("/admin/login").permitAll() // 登录请求不需要认证
                .antMatchers("/file/*").permitAll()
                .anyRequest().authenticated(); // 其余请求都需要认证
        // 退出登录配置
        http.logout()
                .logoutUrl("/admin/logout") // 注销的路径
                .logoutSuccessHandler(new MyLogoutSuccessHandler()) // 登出成功处理器
                .clearAuthentication(true) // 清除认证数据
                .invalidateHttpSession(true); // 清除session
        // 异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(new MyAuthenticationEntryPoint()) // 未登录处理器
                .accessDeniedHandler(new MyAccessDeniedHandler()); // 权限不足处理器
        // 关闭csrf防护,取消跨站请求伪造防护
        http.csrf().disable();
        // 开启跨域访问
        http.cors();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

image.gif

认证授权逻辑

@Service
public class MyUserDetailService implements UserDetailsService {
    @DubboReference
    private AdminService adminService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.认证
        Admin admin = adminService.findByName(username);
        if(admin == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if (!admin.isStatus()) {
            throw new UsernameNotFoundException("用户不可用");
        }
        // 2.授权
        List<Permission> permissions = adminService.findAllPermission(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
        }
        // 3.封装为UserDetails对象
        UserDetails userDetails = User.withUsername(admin.getUsername())
                .password(admin.getPassword())
                .authorities(grantedAuthorities)
                .build();
        // 4.返回封装好的UserDetails对象
        return userDetails;
    }
}

image.gif

权限不足处理器

/**
 * 权限不足处理器
 */
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        BaseResult result = new BaseResult(403, "权限不足", null);
        response.getWriter().write(JSON.toJSONString(result));
    }
}

image.gif

未登录处理器

/**
 * 未登录处理器
 */
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        BaseResult result = new BaseResult(401, "用户未登录,请登录", null);
        response.getWriter().write(JSON.toJSONString(result));
    }
}

image.gif

登录失败处理器

/**
 * 登录失败处理器
 */
public class MyLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        BaseResult result = new BaseResult(402, "用户名或密码错误", null);
        response.getWriter().write(JSON.toJSONString(result));
    }
}

image.gif

登录成功处理器

/**
 * 登录成功处理器
 */
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        BaseResult result = new BaseResult(200, "登录成功", userDetails);
        response.getWriter().write(JSON.toJSONString(result));
    }
}

image.gif

登出成功处理器

/**
 * 登出成功处理器
 */
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        BaseResult result = new BaseResult(200, "注销成功", null);
        response.getWriter().write(JSON.toJSONString(result));
    }
}

image.gif


相关文章
|
8月前
swagger接口需要权限验证解决方案
当我们在使用swagger的情况下,经常会遇到需要授权或者请求带有token才可以访问接口,这里我们就是解决授权问题。
184 0
|
12月前
|
安全 NoSQL Java
SpringBoot3整合SpringSecurity,实现自定义接口权限过滤(二)
SpringBoot3整合SpringSecurity,实现自定义接口权限过滤
785 0
|
12月前
|
安全 Java 数据库连接
四.SpringSecurity基础-自定义登录流程
SpringSecurity基础-自定义登录流程
|
12月前
|
前端开发 JavaScript Java
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回
本篇将要学习 Spring Boot 统一功能处理模块,这也是 AOP 的实战环节 用户登录权限的校验实现接口 HandlerInterceptor + WebMvcConfigurer 异常处理使用注解 @RestControllerAdvice + @ExceptionHandler 数据格式返回使用注解 @ControllerAdvice 并且实现接口 @ResponseBodyAdvice
441 0
|
11月前
springsecurity的接口编写
springsecurity的接口编写
41 0
|
12月前
|
存储 SQL 数据库
SpringSecurity基础-记住我功能实现
Remember me(记住我)记住我,当用户发起登录勾选了记住我,在一定的时间内再次访问该网站会默认登录成功,即使浏览器退出重新打开也是如此,这个功能需要借助浏览器的cookie实现,具体流程如下
58 0
|
12月前
|
存储 SQL 数据库
七.SpringSecurity基础-记住我功能实现
SpringSecurity基础-记住我功能实现
|
12月前
|
存储 缓存 安全
SpringBoot3整合SpringSecurity,实现自定义接口权限过滤(一)
SpringBoot3整合SpringSecurity,实现自定义接口权限过滤
764 0
|
消息中间件 JavaScript 小程序
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回 下
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回 下
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回 下
|
JavaScript 前端开发 小程序
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回 上
SpringBoot 统一功能处理:用户登录权限校验-拦截器、异常处理、数据格式返回 上