欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

shiro前后端分离后端部分代码

程序员文章站 2022-07-15 16:10:59
...

shiro前后端分离mavenWeb项目使用,以下是简单思路

首先需要导入包两个

    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-all</artifactId>
        <version>1.4.0</version>
        <type>pom</type>
    </dependency>
    <!-- shiro与Spring的集成包 -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.0</version>
    </dependency>

shiro配置文件要配置

<?xml version="1.0" encoding="UTF-8"?>

<!--shiro安全管理器,核心组件-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
  <property name="realm" ref="CRMRealm" />
    <property name="sessionManager" ref="sessionManager"/>
</bean>

<!--自定义的realm-->
<bean id="CRMRealm" class="cn.itsource.crm.web.shiro.CRMRealm">
    <property name="name" value="CRMRealm"/>
    <!--凭证匹配器-->
    <property name="credentialsMatcher">
        <!--可以免密匹配器-->
        <bean class="cn.itsource.crm.web.shiro.MyHashedCredentialsMatcher">
            <property name="hashAlgorithmName" value="MD5"/>
            <property name="hashIterations" value="10" />
        </bean>
    </property>
</bean>

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
      depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>


<!--shiro的真正过滤器,这里在控制,是否可以访问-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="http://localhost:8080/login#/login"/>
    <!--没有权限跳转到此页面-->
  <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    <!--需要拦截和放行的资源-->
    <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap" />
    <!--这里是配置所有的自定义过滤器-->
    <property name="filters">
        <map>
            <entry key="myAuthc" value-ref="CRMAuthenticationFilter"/>
            <entry key="crm" value-ref="CRMNoPermissionFilter"/>
        </map>
    </property>
</bean>

<!--实例工厂方法工厂的一个方法的返回值当做一个bean,返回map给shiro过滤器-->
<bean id="filterChainDefinitionMapFactory" class="cn.itsource.crm.web.shiro.FilterChainDefinitionMap" />
<bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapFactory" factory-method="returnMap" />


<!--自定义的session,Manager-->
<bean id="sessionManager" class="cn.itsource.crm.web.shiro.CrmSessionManager"/>

<!--自定义的认证过滤器-->
<bean id="CRMAuthenticationFilter" class="cn.itsource.crm.web.shiro.CRMAuthenticationFilter"/>

<!--权限过滤器-->
<bean id="CRMNoPermissionFilter" class="cn.itsource.crm.web.shiro.CRMNoPermissionFilter"></bean>

配置需要的几个主要类
shiro前后端分离后端部分代码

realm数据源是自定义的

public class CRMRealm extends AuthorizingRealm {

@Autowired
private IEmployeeService employeeService;

/**权限认证
 * @param principalCollection
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("该用户所有的sn");
    //    拿到当事人(用户)名称
    Employee employee = (Employee)principalCollection.getPrimaryPrincipal();
    //    创建一个授权信息对象,需要传入角色和权限
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    //    根据用户名拿到权限信息
    List<String> permission = employeeService.getPermissions(employee.getId());
    System.out.println(permission);
    //    传入到授权信息对象中
    authorizationInfo.addStringPermissions(permission);
    return authorizationInfo;
}

/**登录验证进入此方法
 * @param authenticationToken
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("登录认证");

// 传入的是usernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
// 通过token拿到登录用户名
String username = token.getUsername();
// 根据用户名去拿密码(到数据库中)
Employee employee = employeeService.queryByUsername(username);
if (employee == null) {
// 如果根据用户名查询出来的对象为null ,就代表该用户名错误/或者不存在
return null;
}
// 设置盐,盐值为group5
ByteSource salt = ByteSource.Util.bytes(“group5”);
//设置到userContext以便调用
UserContext.setUser(employee);
// 创建一个AuthenticationInfo, 三个参数分别是 需要记住的用户 /根据用户名查询出来的密码/ realm getName 是去拿配置文件realm的名称
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(employee,employee.getPassword(),salt,getName());
return simpleAuthenticationInfo;
}
}

过滤器自定义,以及放行

public class FilterChainDefinitionMap {
@Autowired
private PermissionMapper permissionMapper;

public  Map<String,String> returnMap(){
    Map<String,String>  map= new LinkedHashMap<>();

// 前端的登录认证地址
map.put("/login", “anon”); //anon代表不登录也可以访问
map.put("/logout", “anon”); //anon代表不登录也可以访问
map.put("/wxLogin", “anon”);
map.put("/callback", “anon”);
map.put("/bind", “anon”);
map.put("/systemMenu/permission", “anon”);
map.put("/fileUpLoad/saveImg", “anon”);
map.put("//employee/tenant", “anon”);
// 查询出所有的权限和资源
List permissions = permissionMapper.findAll();
// 遍历这个list
for (Permission permission : permissions) {
map.put(permission.getUrl(),“crm[”+ permission.getSn()+"]");
}
map.put("/**", “myAuthc”); //myAuthc 代表登录后options请求可以访问
return map;
}

}

前后端分离后的session管理自定义,接受前端传回的sessionid

/**

  • 自定义的shiro session 管理器
    */
    public class CrmSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = “X-Token”;

    private static final String REFERENCED_SESSION_ID_SOURCE = “Stateless request”;

    public CrmSessionManager() {
    super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
    //取到jessionid
    String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
    HttpServletRequest request1 = (HttpServletRequest) request;
    //如果请求头中有 X-TOKEN 则其值为sessionId
    if (!StringUtils.isEmpty(id)) {
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
    return id;
    } else {
    //否则按默认规则从cookie取sessionId
    return super.getSessionId(request, response);
    }
    }

}

权限拦截器

public class CRMNoPermissionFilter extends PermissionsAuthorizationFilter {

/**
 * 当用户没有权限或者没有登录(登录过期)进入此方法
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
        resp.setStatus(HttpStatus.OK.value());
        return true;
    }
    //前端Ajax请求时requestHeader里面带一些参数,用于判断是否是前端的请求
    String ajaxHeader = req.getHeader("X-Requested-With");
    System.out.println(req.getHeader("X-Token"));
    if (ajaxHeader != null || req.getHeader("X-Token") != null) {
        //前端Ajax请求,则不会重定向
        resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setContentType("application/json; charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("{\"success\":false,\"msg\":\"权限不够\"}");
        out.flush();
        out.close();
        return false;
    }
    return super.onAccessDenied(request, response);
}

}

自定义的认证过滤器

/**

  • CRM 自定义的认证过滤器
    */
    public class CRMAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    //如果是OPTIONS请求,直接放行
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String method = httpServletRequest.getMethod();
    if(“OPTIONS”.equalsIgnoreCase(method)){
    return true;
    }
    return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected AuthenticationToken createToken(String username, String password, ServletRequest request, ServletResponse response) {
    //是否记住我
    boolean rememberMe = isRememberMe(request);
    //主机信息
    String host = getHost(request);
    //需要密码登录
    String loginType = LoginType.PASSWORD;

     //重新获取请求的值
     String reqLoginType = request.getParameter("loginType");
     if(reqLoginType != null && !"".equals(reqLoginType)){
         loginType = reqLoginType;
     }
     //封装token
     MyUserPassToken token = new MyUserPassToken(username, password, loginType, rememberMe, host);
     return token;
    

    }
    }