springboot整合shiro认证授权

shiro认证授权

第一步:在web的工程下引入依赖

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-all</artifactId>
  <version>1.3.2</version>
</dependency>

第二步:在web.xml配置一个过滤器代理,(这个代理是属于spring-web.jar里的 )

<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

第三步: 配置shiro的过滤器bean(重点面试:我配置bean的时候配置在了springmvc中,不行,但是配置在spring中可以,这就是spring父子容器问题)

<!-- 配置shiro的过滤器bean -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
   <property name="securityManager" ref="securityManager"></property>
   <!-- 登录页面路径 -->
   <property name="loginUrl" value="/login.jsp"/>
   <!-- 登录成功后显示的路径 -->
   <property name="successUrl" value="/index.jsp"></property>
   <!-- 未授权的页面提示 -->
   <property name="unauthorizedUrl" value="/unauthorize.jsp"></property>
   <!-- url拦截规则  -->
   <property name="filterChainDefinitions">
      <value>
       /validatecode.jsp* = anon       
       /login.jsp = anon
       /sysUser/login.action = anon
       /js/** = anon
       /images/** = anon
       /css/** = anon
       /json/* = anon
       /** = authc 注意一个*和两个*的区别
      </value>
   </property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
</bean>

第四步写登录接口,登录成功存session里边

@RequestMapping(value = "login.action",method = {RequestMethod.POST,RequestMethod.GET})
public String login(HttpServletRequest request, SysUser sysUser,@RequestParam String checkcode){
    String key = (String)request.getSession().getAttribute("key");
    if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){
        //验证码正确
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUser.getUsername(), sysUser.getPassword());(可加密)
        try {
            subject.login(usernamePasswordToken);
        }catch (AuthenticationException e){
            return "redirect:/login.jsp";
        }
        SysUser principal = (SysUser)subject.getPrincipal();
        request.getSession().setAttribute("username",principal.getUsername());(可存当前用户全部信息)
        return "common/index";
    }else {


        return "redirect:/login.jsp";
    }
}

第五步在 在spring配置 securityMananger中配置一个realm(认证授权代码)

<!-- shior登录认证授权 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="zjsRealm"></property>
</bean>
<bean id="zjsRealm" class="com.zjs.realm.ZjsRealm"></bean>

第六步认证授权代码realm
@Component
public class ZjsRealm extends AuthorizingRealm {


@Autowired
private SysUserMapper sysUserMapper;

@Autowired
private SysUserRoleMapper sysUserRoleMapper;

@Autowired
private SysAuthRoleMapper sysAuthRoleMapper;


@Autowired
private SysRoleFunctionMapper sysRoleFunctionMapper;

@Autowired
private SysAuthFunctionMapper sysAuthFunctionMapper;

//权限认证
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

SysUser sysUser = (SysUser)principalCollection.getPrimaryPrincipal();
String id = sysUser.getId();
//查询当前sysUser所拥有的所有角色和权限
SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
SysUserRoleExample.Criteria criteria = sysUserRoleExample.createCriteria();
criteria.andUserIdEqualTo(id);
List<SysUserRoleKey> roles = this.sysUserRoleMapper.selectByExample(sysUserRoleExample);

//角色信息集合
List<String> rolesStringList=new ArrayList<>();


//权限信息集合
List<String> functionStringList=new ArrayList<>();


if(null != roles && roles.size()>0){

//角色信息 添加完成---------
for(SysUserRoleKey sysUserRoleKey:roles){
SysAuthRole sysAuthRole = this.sysAuthRoleMapper.selectByPrimaryKey(sysUserRoleKey.getRoleId());
rolesStringList.add(sysAuthRole.getCode());

//权限添加------------
SysRoleFunctionExample sysRoleFunctionExample = new SysRoleFunctionExample();
SysRoleFunctionExample.Criteria criteria1 = sysRoleFunctionExample.createCriteria();
criteria1.andRoleIdEqualTo(sysUserRoleKey.getRoleId());
List<SysRoleFunctionKey> sysRoleFunctionKeys = this.sysRoleFunctionMapper.selectByExample(sysRoleFunctionExample);

if(null != sysRoleFunctionKeys && sysRoleFunctionKeys.size()>0){

for(SysRoleFunctionKey sysRoleFunctionKey:sysRoleFunctionKeys){
SysAuthFunction sysAuthFunction = this.sysAuthFunctionMapper.selectByPrimaryKey(sysRoleFunctionKey.getFunctionId());
functionStringList.add(sysAuthFunction.getCode());(注解控制的字段,下方controller中有,第八步)
}

}
}

}
simpleAuthorizationInfo.addRoles(rolesStringList);
simpleAuthorizationInfo.addStringPermissions(functionStringList);



return simpleAuthorizationInfo;
}

//登录验证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;

String username = usernamePasswordToken.getUsername();

//查询数据库
SysUserExample sysUserExample = new SysUserExample();
sysUserExample.createCriteria().andUsernameEqualTo(username);
List<SysUser> sysUsers = this.sysUserMapper.selectByExample(sysUserExample);
if(sysUsers.size()>=1){
SysUser sysUser = sysUsers.get(0);
return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), getName());
}

return null;
}
}

第七步权限控制注解使用在mvc的bean中配置

<!--shior 注解使用-->
<bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<!-- 必须改为true,即使用cglib方式为Action创建代理对象。默认值为false,使用JDK创建代理对象,会造成问题 -->
<property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>

第八步:注解控制接口

//查询分页
@RequestMapping("findPage.action")
@ResponseBody
@RequiresRoles("chengxuyuan")
public Map<String,Object> findPage(PageQuery pageQuery){
PageInfo<BcStaff> pageInfo = bcStaffService.pageselect(pageQuery);
Map<String, Object> map = new HashMap<>();
map.put("total",pageInfo.getTotal());
map.put("rows",pageInfo.getList());
return map;
}

猜你喜欢

转载自blog.csdn.net/csdn_667/article/details/103620770