Java 杂谈shiroSSM+shiro等

Spring boot集成shiro

2019-09-17  本文已影响0人  Wocus

shiro为apache旗下一个权限框架,Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理.有三个核心组件:Subject,SecurityManager 和 Realms。

第一步:引入jar包,我这里使用的是gradle
implementation 'org.apache.shiro:shiro-spring:1.3.2'
第二步:配置shiro
package com.sansence.redwine.config;

import com.sansence.redwine.shiro.MyAuthenticationFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: shiro03
 * @description: 权限配置
 * @author: jiang wei
 * @create: 2019-04-24 14:13
 */
@Configuration
public class ShiroConfig {

    /**
     * 配置接口权限
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/admin-info/401");//设置登录界面
        shiroFilterFactoryBean.setUnauthorizedUrl("/manager/login.html");//设置无权限界面

        Map<String, Filter> filter = new LinkedHashMap<>();
        filter.put("authc",new ShiroLoginFilter());
        shiroFilterFactoryBean.setFilters(filter);
        Map<String,String> filterMap=new LinkedHashMap<>();
        filterMap.put("/logs/**","authc");
        filterMap.put("/product/**","authc");
        filterMap.put("/admin-info/login","anon");
        filterMap.put("/admin-info/401","anon");
        filterMap.put("/admin-info/**","authc");
        filterMap.put("/adminware/**","authc");
        filterMap.put("/unit/**","authc");
        filterMap.put("/customer/**","authc");
        filterMap.put("/repertory/**","authc");
        filterMap.put("/role/**","authc");
        filterMap.put("/permission/**","authc");
        filterMap.put("/species/**","authc");
        filterMap.put("/user/**","authc");
        filterMap.put("/userrecord/**","authc");
        filterMap.put("/ware/**","authc");
        filterMap.put("/warerecord/**","authc");
        filterMap.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 注入权限管理
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    @Bean
    public CustomRealm customRealm(){
        return new CustomRealm();
    }
}

以上的权限配置,常用的有以下几种
anon:公开
authc:需认证才可访问
perms:需要哪些权限才能访问例如perms[admin:update,admin:select]
role:要什么角色才可以访问例如role[admin]

登录,授权类

package com.sansence.redwine.config;

import com.sansence.redwine.entity.Admin;
import com.sansence.redwine.service.IAdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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;

import java.util.HashSet;
import java.util.Set;

/**
 * @program: shiro03
 * @description: 权限认证
 * @author: jiang wei
 * @create: 2019-04-24 14:04
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private IAdminService iAdminService;

    /**
     * 获取用户所拥有权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //String username= (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        String role="admin";
        Set<String> set=new HashSet<>();
        set.add(role);
        info.setRoles(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        Admin admin=iAdminService.selectAdminByAccount(token.getPrincipal().toString());
        if (admin==null){
            throw new AccountException("该账号不存在");
        }
        if (!admin.getAdminPassword().equals(new String((char[]) token.getCredentials()))){
            throw new AccountException("密码不正确");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(),admin.getAdminPassword(),getName());
    }
}

第三步:登录与退出登录

package com.sansence.redwine.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sansence.redwine.config.BaseErrorException;
import com.sansence.redwine.entity.Admin;
import com.sansence.redwine.entity.Permission;
import com.sansence.redwine.entity.Role;
import com.sansence.redwine.intercoptor.LogWeb;
import com.sansence.redwine.service.IAdminService;
import com.sansence.redwine.service.IPermissionService;
import com.sansence.redwine.service.IRoleService;
import com.sansence.redwine.util.ResultData;
import com.sansence.redwine.util.Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  管理员接口
 * </p>
 * @author wocus
 * @since 2019-05-16
 */
@RestController
@Api(tags = "管理员接口")
@RequestMapping("/admin-info")
public class AdminController {


    @Autowired
    private IAdminService iAdminServic;



    @PostMapping("/login")
    @LogWeb("管理员登录")
    @ApiOperation("管理员登录")
    public ResultData login(@RequestBody Admin admin){
        if (admin.getAdminAccount()==null){
            throw new BaseErrorException(-101,"请输入账号");
        }else if(admin.getAdminPassword()==null){
            throw new BaseErrorException(-101,"请输入密码");
        }
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("adminAccount",admin.getAdminAccount());
        queryWrapper.eq("adminPassword",admin.getAdminPassword());
        Subject subject=SecurityUtils.getSubject();

        UsernamePasswordToken token=new UsernamePasswordToken(admin.getAdminAccount(),admin.getAdminPassword());
        try {
            subject.login(token);
            Session session=subject.getSession();
            session.setAttribute("account",admin.getAdminAccount());
            Admin admin1=iAdminServic.getOne(queryWrapper);
            admin1.setAdminEndLoginTime(Utils.getDateTime());
            iAdminServic.updateById(admin1);
            return ResultData.success(admin1,"登录成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.errorParam("账号与密码不匹配");
        }
    }

    @PostMapping("/logout")
    @LogWeb("管理员退出登录")
    @ApiOperation("管理员退出登录")
    public ResultData logout(){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return ResultData.result(1);
    }
}

到这里就完成了,下一文章讲在ajax中如何实现权限验证

上一篇下一篇

猜你喜欢

热点阅读