
这部分网上资料较多,不再赘述;

用户拥有1或多个角色,一个角色拥有多种权限。






查询角色及权限代码示例
public UserDetails loadUserByUsername(String usename) throws UsernameNotFoundException {
// 查询数据库
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username",usename);
UserInfo userInfo = userInfoDao.selectOne(queryWrapper);
if (userInfo ==null) {
throw new UsernameNotFoundException("用户不存在");
}
// 获取用户角色
List<String> roles = rolePermissionDao.getRuleByUserId(userInfo.getId());
// 获取用户权限(url)
List<String> per = rolePermissionDao.getPermissByUserId(userInfo.getId());
for (String role : roles) {
per.add("ROLE_"+role);
}
List<GrantedAuthority> auths = new ArrayList<>();
for (String s : per) {
GrantedAuthority e = new SimpleGrantedAuthority(s);
auths.add(e);
}
// 返回认证主体UserDetails
return new User(userInfo.getUsername(),userInfo.getPassword(),auths);
//使用非自定义的密码,可能需要进行加密后再放置进认证主体密码属性中去
// return new User(userInfo.getUsername(),bCryptPasswordEncoder.encode(userInfo.getPassword()),auths);
}查询角色及权限相关sql:
import cn.com.demo.entity.RolePermission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface RolePermissionDao extends BaseMapper<RolePermission> {
/**
* 获取用户角色
* @param userId
* @return
*/
@Select({"SELECT ri.role_name FROM user_role ur INNER JOIN role_info ri ON ri.id = ur.role_id " +
" WHERE ur.user_id = #{userId}"})
List<String> getRuleByUserId(Integer userId);
/**
* 获取用户权限
* @param userId
* @return
*/
@Select({"SELECT per.permiss_value FROM user_role ur INNER JOIN role_permission rp ON ur.role_id = rp.role_id" +
" INNER JOIN permission_info per ON per.id = rp.per_id" +
" WHERE ur.user_id = #{userId}"})
List<String> getPermissByUserId(Integer userId);
}import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
// 开启鉴权注解
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
// 配置MybatisMapper扫描路径
@MapperScan("cn.com.demo.dao.**")
@SpringBootApplication(scanBasePackages = "cn.com.demo.**")
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class,args);
}
}import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/test")
public String test(){
return "OK";
}
@GetMapping("/info")
public String info(){
return SecurityContextHolder.getContext().getAuthentication().getName();
}
@GetMapping("/p1")
@Secured({"ROLE_admin"})
//@PreAuthorize("hasAnyAuthority('p1')")
public String p1(){
return "p1";
}
@GetMapping("/p2")
@Secured({"ROLE_test"})
//@PreAuthorize("hasAnyAuthority('p2')")
public String p2(){
return "p2";
}
@GetMapping("/t1")
@PreAuthorize("hasAnyAuthority('/demo/t1')")
public String t1(){
return "t1";
}
@GetMapping("/t2")
@PreAuthorize("hasAnyAuthority('/demo/t2')")
public String t2(){
return "t2";
}
}用户 | 角色 | 权限 | 可访问地址 |
|---|---|---|---|
admin | admin | /demo/t1 | /demo/t1,/demo/p1 |
test | test | /demo/t2 | /demo/t2,/demo/p2 |