设置资源所需权限与封装权限信息

设置资源所需权限

    限制访问资源所需权限SpringSecurity为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的的方式。我们可以使用注解去指定对方的资源

    所需的权限

    但是要使用它我们需要先开启相关配置

    

@EnableGlobalMethodSecurity(prePostEnabled = true)

 

然后就可以使用对应的注解。@PreAuthorize

package com.example.qinghuatokendemo.Controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    @PreAuthorize("hasAuthority('test')")
    public String hello(){
        return "Hello Security";
    }
}

封装权限信息

      我们前面在写UserDetailsServiceImpl的时候说过,在查询出用户后还要获取对应的权限信息,封装到UserDetails中返回。

​      我们先直接把权限信息写死封装到UserDetails中进行测试。

​      我们之前定义了UserDetails的实现类LoginUser,想要让其能封装权限信息就要对其进行修改。

package com.example.qinghuatokendemo.Domain;


import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
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.stream.Collectors;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities!=null){
            return authorities;
        }
        //把parmissions中Spring类型的权限信息封装SimpleGrantedAuthority对象
       /*   authorities = new ArrayList<>();
            for (String parmissions: permissions ){
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(parmissions);
                authorities.add(authority);
        }*/
         authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

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

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

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

    @Override
    public boolean isEnabled() {
        return true;
    }


}

 

 

 

 LoginUser修改完后我们就可以在UserDetailsServiceImpl中去把权限信息封装到LoginUser中了。我们写死权限进行测试,后面我们再从数据库中查询权限信息。

package com.example.qinghuatokendemo.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.qinghuatokendemo.Domain.LoginUser;
import com.example.qinghuatokendemo.Domain.User;
import com.example.qinghuatokendemo.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //查询对应的权限信息
        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));

        //把数据封装成UserDetails返回
        return new LoginUser(user,list);
    }
}

 

posted @ 2023-04-25 20:16  zj勇敢飞,xx永相随  阅读(19)  评论(0编辑  收藏  举报