Enable the annotation

@EnableGlobalMethodSecurity(prePostEnabled = true)
Copy the code

Normal enable just turn on that annotation and drop my configuration

package com.fedtech.sys.provider.config.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;

/** * Resource configuration **@author <a href = "mailto:[email protected]" > huan </a >
 * @date 2021/1/13
 * @since1.0.0 * /
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    RedisConnectionFactory redisConnectionFactory;
    @Resource
    private TokenStore tokenStore;

    @Bean
    public TokenStore redisTokenStore(a) {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) { resources.tokenStore(tokenStore); }}Copy the code

role

    /** * Query a single user **@param query {@link UserQuery}
     *
     * @return com.fedtech.common.util.result.R<com.fedtech.sys.provider.view.UserView>
     *
     * @author <a href = "mailto:[email protected]" > huan </a >
     * @date 2021/2/20
     * @since1.0.0 * /
    @GetMapping("select")
    @PreAuthorize("hasAuthority('admin')")
    public R<UserView> selectUser(UserQuery query) {
        UserDto dto = userService.selectUser(query);
        return R.successWithData(userMapper.dto2View(dto));
    }
Copy the code

permissions

The default is DenyAllPermissionEvaluator, all rights to refuse, so to the custom

Custom processing logic

I put the permissions in the custom userDetails

package com.fedtech.common.model;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

/** * This class is safe to return and can provide the user with the information to see, that is, desensitized information **@author <a href = "mailto:[email protected]" > huan </a >
 * @date 2021/1/9
 * @since1.0.0 * /
@Data
@Slf4j
public class SecurityUser implements UserDetails {
    private static final long serialVersionUID = 8689435103879098852L;
    / * * * * / salt
    private String salt;

    /** * User token */
    private String token;

    /** * User status */
    private String status;

    /** * User password */
    private String password;

    /** * User login account */
    private String loginName;

    private Long userId;

    /** * User role **@date 2021/1/10
     * @since1.0.0 * /
    private List<UserRole> roleList;
    /** * Permission list **@date 2021/1/11
     * @since1.0.0 * /
    private List<UserPermission> permissionList;


    /** * Client user **@paramClient Indicates the client@author <a href = "mailto:[email protected]" > huan </a >
     * @date 2021/1/13
     * @since1.0.0 * /
    public SecurityUser(OauthClientDetails client) {
        if(client ! =null) {
            password = client.getClientSecret();
            loginName = client.getClientId();
            String authorities = client.getAuthorities();
            StringTokenizer stringTokenizer = new StringTokenizer(authorities, ",");
            roleList = new ArrayList<>();
            if (stringTokenizer.hasMoreTokens()) {
                UserRole userRole = newUserRole(); userRole.setCode(stringTokenizer.nextToken()); roleList.add(userRole); }}}/** * Common user **@paramUser *@paramRoleList role *@paramPermissionList Permission * *@author <a href = "mailto:[email protected]" > huan </a >
     * @date 2021/1/13
     * @since1.0.0 * /
    public SecurityUser(User user, List<UserRole> roleList, List<UserPermission> permissionList) {
        if(user ! =null) {
            salt = user.getSalt();
            token = user.getToken();
            status = user.getStatus();
            password = user.getPassword();
            loginName = user.getLoginName();
            userId = user.getId();
            this.roleList = roleList;
            this.permissionList = permissionList; }}@Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        if(! CollUtil.isEmpty(roleList)) {for (UserRole role : roleList) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getCode());
                authorities.add(authority);
            }
        }
        log.debug("Obtained user permissions: {}", authorities);
        return authorities;
    }

    @Override
    public String getPassword(a) {
        return password;
    }

    @Override
    public String getUsername(a) {
        return loginName;
    }

    @Override
    public boolean isAccountNonExpired(a) {
        return true;
    }

    @Override
    public boolean isAccountNonLocked(a) {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired(a) {
        return true;
    }

    @Override
    public boolean isEnabled(a) {
        return true; }}Copy the code
package com.fedtech.common.config;

import cn.hutool.core.collection.CollUtil;
import com.fedtech.common.model.SecurityUser;
import com.fedtech.common.model.UserPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;

import java.io.Serializable;
import java.util.List;


/** * Custom permission processing **@author <a href="mailto:[email protected]">huan</a>
 * @version 1.0.0
 * @date2021/2/26 * /
@Slf4j
@Configuration
public class MyPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        SecurityUser principal = (SecurityUser) authentication.getPrincipal();
        List<UserPermission> permissionList = principal.getPermissionList();
        if (CollUtil.isNotEmpty(permissionList)) {
            return permissionList.stream().anyMatch(x -> StringUtils.equals(x.getUrl(), (CharSequence) targetDomainObject) &&
                    StringUtils.equals(x.getCode(), (CharSequence) permission));
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false; }}Copy the code

use

    /** * Query a single user **@param query {@link UserQuery}
     *
     * @return com.fedtech.common.util.result.R<com.fedtech.sys.provider.view.UserView>
     *
     * @author <a href = "mailto:[email protected]" > huan </a >
     * @date 2021/2/20
     * @since1.0.0 * /
    @GetMapping("select")
    @PreAuthorize("hasPermission('/sys/user/insert','userInsert')")
    public R<UserView> selectUser(UserQuery query) {
        UserDto dto = userService.selectUser(query);
        return R.successWithData(userMapper.dto2View(dto));
    }
Copy the code