MENU

SpringBoot整合Apache shiro

基本架构

先来看一下目录
1.jpg

依赖

pom.xml引入依赖

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.2</version>
</dependency>

User Entity

User.java

package com.wanvale.pms.eneity;

import java.util.Set;

public class User {
    private Integer id;
    private String username;
    private String password;
    private Set<Role> roles;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", roles=" + roles +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public User() {
    }

    public User(Integer id, String username, String password, Set<Role> roles) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.roles = roles;
    }
}

Role Entity

Role.java

package com.wanvale.pms.eneity;

import java.util.Set;

public class Role {
    private Integer id;
    private String roleName;
    private Set<Permissions> permissions;

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", permissions=" + permissions +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

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

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

    public Role() {
    }

    public Role(Integer id, String roleName, Set<Permissions> permissions) {
        this.id = id;
        this.roleName = roleName;
        this.permissions = permissions;
    }
}

Permissions Entity

Permissions.java

package com.wanvale.pms.eneity;

public class Permissions {
    private int id;
    private String permissionsName;

    @Override
    public String toString() {
        return "Permissions{" +
                "id=" + id +
                ", permissionsName='" + permissionsName + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

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

    public String getPermissionsName() {
        return permissionsName;
    }

    public void setPermissionsName(String permissionsName) {
        this.permissionsName = permissionsName;
    }

    public Permissions() {
    }

    public Permissions(int id, String permissionsName) {
        this.id = id;
        this.permissionsName = permissionsName;
    }
}

LoginServiceImpl

LoginServiceImpl.java

package com.wanvale.pms.service.impl;

import com.wanvale.pms.eneity.Permissions;
import com.wanvale.pms.eneity.Role;
import com.wanvale.pms.eneity.User;
import com.wanvale.pms.service.LoginService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class LoginServiceImpl implements LoginService {

    public User getUserByUsername(String username){
        //模拟数据库查询
        return getMapByName(username);
    }

    // 模拟从数据库中查询,实际开发写对应的业务逻辑
    private User getMapByName(String userName) {
        //共添加两个用户,两个用户都是admin一个角色,
        //wsl有query和add权限,zhangsan只有一个query权限

        //为admin提供权限:[sys:query][sys:add]
        Permissions permissions1 = new Permissions(1, "sys:query");
        Permissions permissions2 = new Permissions(2, "sys:add");
        Set<Permissions> permissionsSet = new HashSet<>();
        permissionsSet.add(permissions1);
        permissionsSet.add(permissions2);
        //为user提供权限:[sys:query]
        Set<Permissions> permissionsSet1 = new HashSet<>();
        permissionsSet1.add(permissions1);

        //角色:[admin][user]
        Role role = new Role(1, "admin", permissionsSet);
        Role role1 = new Role(2, "user", permissionsSet1);

        //分别添加到roleSet中
        Set<Role> roleSet = new HashSet<>();
        roleSet.add(role);
        Set<Role> roleSet1 = new HashSet<>();
        roleSet1.add(role1);

        //新建两个用户
        User user = new User(1000, "admin", "123456", roleSet);
        User user1 = new User(1001, "test", "123456", roleSet1);

        //新建一个Map用来查询用户
        Map<String, User> map = new HashMap<>();
        map.put(user.getUsername(), user);
        map.put(user1.getUsername(), user1);

        return map.get(userName);
    }
}

LoginService

LoginService.java

package com.wanvale.pms.service.impl;

import com.wanvale.pms.eneity.Permissions;
import com.wanvale.pms.eneity.Role;
import com.wanvale.pms.eneity.User;
import com.wanvale.pms.service.LoginService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class LoginServiceImpl implements LoginService {

    public User getUserByUsername(String username){
        //模拟数据库查询
        return getMapByName(username);
    }

    // 模拟从数据库中查询,实际开发写对应的业务逻辑
    private User getMapByName(String userName) {
        //共添加两个用户,两个用户都是admin一个角色,
        //wsl有query和add权限,zhangsan只有一个query权限

        //为admin提供权限:[sys:query][sys:add]
        Permissions permissions1 = new Permissions(1, "sys:query");
        Permissions permissions2 = new Permissions(2, "sys:add");
        Set<Permissions> permissionsSet = new HashSet<>();
        permissionsSet.add(permissions1);
        permissionsSet.add(permissions2);
        //为user提供权限:[sys:query]
        Set<Permissions> permissionsSet1 = new HashSet<>();
        permissionsSet1.add(permissions1);

        //角色:[admin][user]
        Role role = new Role(1, "admin", permissionsSet);
        Role role1 = new Role(2, "user", permissionsSet1);

        //分别添加到roleSet中
        Set<Role> roleSet = new HashSet<>();
        roleSet.add(role);
        Set<Role> roleSet1 = new HashSet<>();
        roleSet1.add(role1);

        //新建两个用户
        User user = new User(1000, "admin", "123456", roleSet);
        User user1 = new User(1001, "test", "123456", roleSet1);

        //新建一个Map用来查询用户
        Map<String, User> map = new HashMap<>();
        map.put(user.getUsername(), user);
        map.put(user1.getUsername(), user1);

        return map.get(userName);
    }
}

GlobalExceptionHandler

GlobalExceptionHandler.java

package com.wanvale.pms.filter;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    @ResponseBody
    public String errorHandler(Exception e){
        e.printStackTrace();
        return "Error:"+e.getMessage();
    }
}

UserRealm

UserRealm.java

package com.wanvale.pms.shiro;

import com.wanvale.pms.eneity.Permissions;
import com.wanvale.pms.eneity.Role;
import com.wanvale.pms.eneity.User;
import com.wanvale.pms.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名去数据库查询用户信息
        User user = loginService.getUserByUsername(username);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String username = authenticationToken.getPrincipal().toString();
        User user = loginService.getUserByUsername(username);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //验证authenticationToken和simpleAuthenticationInfo的信息
            return new SimpleAuthenticationInfo(username, user.getPassword().toString(), getName());
        }
    }
}

运行结果

注意看地址栏传入的参数和返回的结果

用户名密码输入错误

2.jpg

用户名密码输入正确

3.jpg

使用有权限的账号访问index页

4.jpg

使用无权限的账号访问index页

5.jpg

至此,SpringBoot整合Shiro完成


文章标题:SpringBoot整合Apache shiro
如果文中内容侵犯了您的权益,请及时与博主取得联系进行删除!
本站文章未经许可禁止转载,本文地址:https://blog.wanvale.com/archives/104/

Last Modified: June 20, 2020
Archives QR Code Tip
QR Code for this page
Tipping QR Code