Java17 --- SpringSecurity之授权

目录

一、授权

1.1、基于request的授权

1.2、请求未授权处理

1.3、角色分配

1.4、基于方法授权


一、授权

1.1、基于request的授权

java 复制代码
 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.sessionManagement(session ->
                session.maximumSessions(1)
                        .expiredSessionStrategy(new MySessionInformationExpiredStrategy())
        );//会话并发处理
        httpSecurity.cors(Customizer.withDefaults());//跨域处理
        httpSecurity.authorizeRequests(
                authorize -> authorize
                        .requestMatchers("/getListUser").hasAuthority("USER_LIST")
                        .requestMatchers("/addUser").hasAuthority("USER_ADD")
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );
        httpSecurity.formLogin(
                        //Customizer.withDefaults()//使用表单授权方式
                       //.httpBasic(Customizer.withDefaults());//使用基本授权方式
                form -> form.loginPage("/login")
                        .permitAll()//无需授权就能访问
                        .usernameParameter("name")
                        .passwordParameter("pass")
                        .successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
                        .failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
        );
        httpSecurity.logout(logout ->
                logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
        );
        httpSecurity.exceptionHandling(exception ->
                exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
        httpSecurity.csrf(
                csrf -> csrf.disable()
        );//关闭csrf功能
        return httpSecurity.build();
    }
java 复制代码
 @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name",username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }else {
            Collection<GrantedAuthority> collection = new ArrayList<>();
            collection.add(()->"USER_LIST");
            collection.add(()->"USER_ADD");
            return new org.springframework.security.core.userdetails.User(
                    user.getName(),
                    user.getPassword(),
                    user.getEnabled(),
                    true,//用户账号是否过期
                    true, //用户凭证是否过期
                    true, //用户是否被锁定
                    collection //权限列表
            );
        }
    }

1.2、请求未授权处理

java 复制代码
public class MyAccessDeniedHandler  implements AccessDeniedHandler{
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        HashMap map = new HashMap<>();
        map.put("code",400);
        map.put("message","没有权限");
        //将信息json化
        String jsonString = JSON.toJSONString(map);
        //返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonString);
    }
}
java 复制代码
 httpSecurity.exceptionHandling(exception ->
                exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())//请求未认证处理
                        .accessDeniedHandler(new MyAccessDeniedHandler())//
        );

1.3、角色分配

java 复制代码
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name",username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }else {
           return org.springframework.security.core.userdetails.User
                    .withUsername(user.getName())
                    .password(user.getPassword())
                    .disabled(!user.getEnabled())
                    .credentialsExpired(false)
                    .accountLocked(false)
                    .roles("ADMIN")
                    .build();
        }
    }
java 复制代码
httpSecurity.authorizeRequests(
                authorize -> authorize
//                        .requestMatchers("/getListUser").hasAuthority("USER_LIST")
//                        .requestMatchers("/addUser").hasAuthority("USER_ADD")
                        .requestMatchers("/user/**").hasRole("ADMIN")
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );

1.4、基于方法授权

在配置类中开启

java 复制代码
@EnableMethodSecurity //开启基于方法的授权
public class MySecurityConfig {}

在方法再次控制

java 复制代码
 @GetMapping("/getListUser")
    @PreAuthorize("hasRole('ADMIN')")
    public List<User> getListUser(){
        return userService.list();
    }
    @PostMapping("/addUser")
    @PreAuthorize("hasRole('TOM')")
    public void addUser(@RequestBody User user){
        userService.saveUser(user);
        System.out.println("添加一次");
    }
相关推荐
应用市场2 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑2 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
岁月宁静2 小时前
深度定制:在 Vue 3.5 应用中集成流式 AI 写作助手的实践
前端·vue.js·人工智能
心易行者3 小时前
10天!前端用coze,后端用Trae IDE+Claude Code从0开始构建到平台上线
前端
saadiya~3 小时前
ECharts 实时数据平滑更新实践(含 WebSocket 模拟)
前端·javascript·echarts
fruge3 小时前
前端三驾马车(HTML/CSS/JS)核心概念深度解析
前端·css·html
百锦再3 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
烛阴4 小时前
Lua 模块的完整入门指南
前端·lua
浪里行舟4 小时前
国产OCR双雄对决?PaddleOCR-VL与DeepSeek-OCR全面解析
前端·后端
znhy@1235 小时前
CSS易忘属性
前端·css