shiro 的注解以及授权操作

Shiro注解

  @RequiresAuthenthentication   表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true

  @RequiresUser                         表示当前Subject已经身份验证或者通过记住我登录的
  @RequiresGuest                       表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份


  @RequiresRoles(value = {"admin","user"},logical = Logical.AND)                        表示当前Subject需要角色admin和user
  @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.AND)   

        表示当前Subject需要权限user:update并且user:view

使用shiro注解

  <!--开启shiro注解-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
      depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>
<!--注解权限验证失败不跳转路径问题-->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    unauthorized
                </prop>
            </props>
        </property>
        <!--拼接的时本来要跳转页面下的jsp页面  验证失败要跳转的页面-->
        <property name="defaultErrorView" value="fail"/>
    </bean>

注:
  必须将Shiro注解的开启放置到spring-mvc.xml中(即放在springMVC容器中加载),不然Shiro注解开启无效

shiro授权

在自定义realm中对当前登陆的用户进行授权

 @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        //获得当前登录的用户名
        String username = principalCollection.getPrimaryPrincipal().toString();
        //用户登录时给角色授权
        Set<String> roles = this.userService.queryRolesByUname(username);
        Set<String> permissions = this.userService.queryPermissionsByUname(username);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

猜你喜欢

转载自blog.csdn.net/qq_41277773/article/details/85795742