04. 基于自定义Bean权限控制

基于自定义Bean权限控制

在Web 安全表达式中引用自定义Bean授权
1)定义自定义授权类

package com.po.service.impl;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * 自定义授权类
 */
@Component
public class MyAuthorizationService {

    /**
     * 检查用户是否有对应的访问权限
     *
     * @param authentication 登录用户
     * @param request 请求对象
     * @return
     */

    public boolean check(Authentication authentication, HttpServletRequest request) {

        User user = (User) authentication.getPrincipal();
        // 获取用户所有权限
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        // 获取用户名
        String username = user.getUsername();
        // 如果用户名为admin,则不需要认证
        if (username.equalsIgnoreCase("admin")) {
            return true;
        } else {
            // 循环用户的权限, 判断是否有ROLE_ADMIN权限, 有返回true
            for (GrantedAuthority authority : authorities) {
                String role = authority.getAuthority();
                if ("ROLE_ADMIN".equals(role)) {
                    return true;
                }
            }
        }
        return false;
    }
}

配置类

//使用自定义Bean授权
http.authorizeRequests().antMatchers("/user/**").
access("@myAuthorizationService.check(authentication,request)");

用admin用户可以访问用户管理 用其它用户不可以访问用户管理

携带路径变量

/**
* 检查用户是否有对应的访问权限
*
* @param authentication 登录用户
* @param request 请求对象
* @param id 参数ID
* @return
*/
public boolean check(Authentication authentication, HttpServletRequest request, Integer id) {
    if (id > 10) {
        return false;
    }
    return true;
}

//使用自定义Bean授权,并携带路径参数
http.authorizeRequests().antMatchers("/user/delete/{id}").
access("@myAuthorizationService.check(authentication,request,#id)"); 

 

 

posted @ 2023-03-16 15:36  __破  阅读(26)  评论(0)    收藏  举报