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("添加一次");
    }
相关推荐
你也向往长安城吗1 分钟前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
imLix2 分钟前
RunLoop 实现原理
前端·ios
wayman_he_何大民8 分钟前
初始机器学习算法 - 关联分析
前端·人工智能
karrigan10 分钟前
async/await 的优雅外衣下:Generator 的核心原理与 JavaScript 执行引擎的精细管理
javascript
飞飞飞仔12 分钟前
别再瞎写提示词了!这份Claude Code优化指南让你效率提升10倍
前端·claude
刘永胜是我12 分钟前
node版本切换
前端·node.js
成小白16 分钟前
前端实现表格下拉框筛选和表头回显和删除
前端
wayman_he_何大民17 分钟前
初始机器学习算法 - 聚类分析
前端·人工智能
wycode18 分钟前
Vue2实践(3)之用component做一个动态表单(二)
前端·javascript·vue.js
用户10922571561034 分钟前
你以为的 Tailwind 并不高效,看看这些使用误区
前端