Java17 --- SpringSecurity之授权

目录

一、授权

1.1、基于request的授权

1.2、请求未授权处理 

1.3、角色分配 

1.4、基于方法授权 


一、授权

1.1、基于request的授权

 @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();
    }
 @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、请求未授权处理 

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);
    }
}
 httpSecurity.exceptionHandling(exception ->
                exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())//请求未认证处理
                        .accessDeniedHandler(new MyAccessDeniedHandler())//
        );

1.3、角色分配 

@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();
        }
    }
httpSecurity.authorizeRequests(
                authorize -> authorize
//                        .requestMatchers("/getListUser").hasAuthority("USER_LIST")
//                        .requestMatchers("/addUser").hasAuthority("USER_ADD")
                        .requestMatchers("/user/**").hasRole("ADMIN")
                        .anyRequest() //对所有请求开启授权保护
                        .authenticated() //已认证的请求会自动授权
        );

1.4、基于方法授权 

在配置类中开启

@EnableMethodSecurity //开启基于方法的授权
public class MySecurityConfig {}

在方法再次控制 

 @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("添加一次");
    }

 

 

 

 

 

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭鸭老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值