shiro权限管理+springcloud eureka

文章目录

    • 1.shiro权限管理
    • 2.springcloud eureka

1.shiro权限管理

1.新建shiroConfiguration类,与po、vo包同级

@Configuration
public class ShiroCinfiguration {
     

    //创建realm
    @Bean
    public NewsRealm getRealm(){
     return new NewsRealm();}
    
    //创建安全管理器
    @Bean
    public SecurityManager securityManager(NewsRealm realm){
     
        //使用默认的安全管理器
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realm);
        //将自定义realm交给安全管理器统一调度管理
        return securityManager;
    }

    //配置shiroguol器工厂
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
     
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();
        shiroFilterFactory.setSecurityManager(securityManager);
        //通用配置
        shiroFilterFactory.setLoginUrl("/admin");
        shiroFilterFactory.setUnauthorizedUrl("/admin");
        /*
        * key:请求路径
        * value:过滤器类型
        * */
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/types","perms[user-types]");
        filterMap.put("/admin/news","perms[user-news]");
        filterMap.put("/admin/tags","perms[user-tags]");
        filterMap.put("/admin/login","anon");
        filterMap.put("/admin/**","authc");
        System.out.println(filterMap);
//设置过滤器
        shiroFilterFactory.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactory;

    }

    //开启shiro注解支持
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
     
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}

2.建立role实体类

@Entity
@Table(name="t_role")
public class Role implements Serializable {
     

    private static final long serialVersionUID = 2057484709089375773L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>(0);

    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Permission> permissions = new HashSet<>(0);

    public static long getSerialVersionUID() {
     
        return serialVersionUID;
    }

    public Long getId() {
     
        return id;
    }

    public void setId(Long id) {
     
        this.id = id;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public String getDescription() {
     
        return description;
    }

    public void setDescription(String description) {
     
        this.description = description;
    }

    public Set<User> getUsers() {
     
        return users;
    }

    public void setUsers(Set<User> users) {
     
        this.users = users;
    }

    public Set<Permission> getPermissions() {
     
        return permissions;
    }

    public void setPermissions(Set<Permission> permissions) {
     
        this.permissions = permissions;
    }
}

3.建立permission实体类

@Entity
@Table(name="t_permission")
public class Permission implements Serializable{
     

    private static final long serialVersionUID = 423698596935410559L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String code;
    private String description;

    public static long getSerialVersionUID() {
     
        return serialVersionUID;
    }

    public Long getId() {
     
        return id;
    }

    public void setId(Long id) {
     
        this.id = id;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public String getCode() {
     
        return code;
    }

    public void setCode(String code) {
     
        this.code = code;
    }

    public String getDescription() {
     
        return description;
    }

    public void setDescription(String description) {
     
        this.description = description;
    }
}

4.数据库填上数据
role表
shiro权限管理+springcloud eureka_第1张图片
permission表
在这里插入图片描述role_permission表
shiro权限管理+springcloud eureka_第2张图片
user_role表
shiro权限管理+springcloud eureka_第3张图片
user表
在这里插入图片描述5.logincontroller类修改

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password,
                        HttpSession session, RedirectAttributes attributes){
     
//        User user = userService.checkUsers(username,password);
//        if (user!=null){
     
//            user.setPassword(null);
//            session.setAttribute("user",user);
//            return "admin/index";
//        }else {
     
//            attributes.addFlashAttribute("message","用户名或密码错误");
//            return "redirect:/admin";
//        }
        try{
     
            //构造登陆令牌
            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
            //获取subject
            Subject subject = SecurityUtils.getSubject();
            subject.login(upToken);
            User user = (User) subject.getPrincipal();
            session.setAttribute("user",user);
            return "admin/index";
        }catch (Exception e){
     
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/admin";
        }
    }

6.注释掉interceptor包下的两个类
shiro权限管理+springcloud eureka_第4张图片

2.springcloud eureka

1.创建model
shiro权限管理+springcloud eureka_第5张图片
2.如图勾选
shiro权限管理+springcloud eureka_第6张图片shiro权限管理+springcloud eureka_第7张图片3.添加依赖
shiro权限管理+springcloud eureka_第8张图片
4.建立好后在pom.xml文件中添加以下依赖

    <dependency>
        <groupId>tk.mybatisgroupId>
        <artifactId>mapper-spring-boot-starterartifactId>
        <version>2.0.4version>
    dependency>

5.如下建立包
shiro权限管理+springcloud eureka_第9张图片
6.po包中建立user实体类

@Table(name = "tb_user")
public class User implements Serializable {
     

    private static final long serialVersionUID = 532052702063464346L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private  String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private Date created;
    private Date updated;

    public static long getSerialVersionUID() {
     
        return serialVersionUID;
    }

    public Long getId() {
     
        return id;
    }

    public void setId(Long id) {
     
        this.id = id;
    }

    public String getUsername() {
     
        return username;
    }

    public void setUsername(String username) {
     
        this.username = username;
    }

    public String getPassword() {
     
        return password;
    }

    public void setPassword(String password) {
     
        this.password = password;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public Integer getAge() {
     
        return age;
    }

    public void setAge(Integer age) {
     
        this.age = age;
    }

    public Integer getSex() {
     
        return sex;
    }

    public void setSex(Integer sex) {
     
        this.sex = sex;
    }

    public Date getBirthday() {
     
        return birthday;
    }

    public void setBirthday(Date birthday) {
     
        this.birthday = birthday;
    }

    public Date getCreated() {
     
        return created;
    }

    public void setCreated(Date created) {
     
        this.created = created;
    }

    public Date getUpdated() {
     
        return updated;
    }

    public void setUpdated(Date updated) {
     
        this.updated = updated;
    }
}

7.mapper包中UserMapper类

@org.apache.ibatis.annotations.Mapper
public interface UserMappper extends Mapper<User> {
     

}

8.Service包下建立UserService类

@Service
public class UserService {
     

    @Autowired(required = false)
    private UserMappper userMappper;

    public User queryById(Long id){
     
        return this.userMappper.selectByPrimaryKey(id);
    }
}

9在Controller包中新建UserController.类

@RestController
@RequestMapping("user")
public class UserController {
     
    
    @Autowired
    private UserService userService;
    
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
     
        return this.userService.queryById(id);
    }
}

10.对application.yml文件进行数据库连接配置:

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db3?useSSL=true&characterEncoding=utf-8
    username: root
    password: 999
    driver-class-name: com.mysql.jdbc.Driver
  application:
    name: service-provider   #应用名称,注册到eureka后的服务名称
mybatis:
  type-aliases-package: com.lc.service.provider.po
eureka:
  client:
    service-url:  #EurekaServer地址
      defaultZone: http://localhost:10086/eureka

你可能感兴趣的:(shiro,spring,boot,java)