• Springboot+shiro配置笔记+错误小结


      软件152 尹以操

      springboot不像springmvc,它没有xml配置文件,那该如何配置shiro呢,其实也不难,用java代码+注解来解决这个问题。仅以此篇记录我对shiro的学习,如有对过客造成不便,实在抱歉!

      一、加入jar包

      既然要用到shiro,当然要加入它的jar包咯,在pom.xml中jar包依赖中加入:

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

      二、写实体类

      这需要三个实体类,hibernate自动生成5个表

      User实体(用户):

    复制代码
    package com.cy.coo.bean;
    

    import java.util.List;

    import javax.persistence.Column;

    import javax.persistence.Entity;

    import javax.persistence.FetchType;

    import javax.persistence.GeneratedValue;

    import javax.persistence.Id;

    import javax.persistence.JoinColumn;

    import javax.persistence.JoinTable;

    import javax.persistence.ManyToMany;

    import com.fasterxml.jackson.annotation.JsonBackReference;

    @Entity

    public class User {

    @Id</br>
    @GeneratedValue</br>
    </span><span style="color: #0000ff">private</span> Integer user_id;<span style="color: #008000">//</span><span style="color: #008000">用户序号</span>
    



    @Column(unique
    =true)

    private String name;//账户

    <span style="color: #0000ff">private</span> String password;<span style="color: #008000">//</span><span style="color: #008000">密码</span></br></br>
    
    <span style="color: #0000ff">private</span> String salt;<span style="color: #008000">//</span><span style="color: #008000">盐</span></br></br>
        
    <span style="color: #0000ff">private</span> Integer state;<span style="color: #008000">//</span><span style="color: #008000">用户状态</span></br></br>
    
    <span style="color: #0000ff">private</span> String createtime;<span style="color: #008000">//</span><span style="color: #008000">创建时间</span>
    



    @ManyToMany(fetch
    =FetchType.EAGER)//立即从数据库中进行加载数据;
    @JoinTable(name="User_Role",joinColumns={@JoinColumn(name="user_id")},

    inverseJoinColumns
    ={@JoinColumn(name="role_id")})

    private List<Role> roleList;

    @JsonBackReference</br>
    </span><span style="color: #0000ff">public</span> List&lt;Role&gt;<span style="color: #000000"> getRoleList(){</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> roleList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> setRoleList(List&lt;Role&gt;<span style="color: #000000"> roleList){</br>
        </span><span style="color: #0000ff">this</span>.roleList=<span style="color: #000000">roleList;</br>
    }</br>
    


    注:其它getter和setter省略</span><span style="color: #000000">
    

    }

    复制代码

      关于为什么要在getRolelist这个方法上加上@JsonBackReference注解,可以查看这篇文章http://blog.csdn.net/maxu12345/article/details/45538157

      Role实体(角色):

    复制代码
    package com.cy.coo.bean;

    import java.io.Serializable;

    import java.util.ArrayList;

    import java.util.List;

    import javax.persistence.Entity;

    import javax.persistence.FetchType;

    import javax.persistence.GeneratedValue;

    import javax.persistence.Id;

    import javax.persistence.JoinColumn;

    import javax.persistence.JoinTable;

    import javax.persistence.ManyToMany;

    import com.fasterxml.jackson.annotation.JsonBackReference;

    @Entity

    public class Role implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id</br>
    @GeneratedValue</br>
    </span><span style="color: #0000ff">private</span> Integer role_id;<span style="color: #008000">//</span><span style="color: #008000">角色序号</span></br></br>
    
    <span style="color: #0000ff">private</span> String role_name;<span style="color: #008000">//</span><span style="color: #008000">角色名称</span></br></br>
    
    <span style="color: #0000ff">private</span> String role_description;<span style="color: #008000">//</span><span style="color: #008000">角色描述</span>
    



    @ManyToMany

    @JoinTable(name
    = "User_Role", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = {

    @JoinColumn(name
    = "user_id") })

    private List<User> userList=new ArrayList<>();

    @ManyToMany<span style="color: #ff0000">(fetch</span></span><span style="color: #ff0000">=</span><span style="color: #000000"><span style="color: #ff0000">FetchType.EAGER)</span></br>
    @JoinTable(name</span>="Role_Function",joinColumns={@JoinColumn(name="role_id")},inverseJoinColumns=<span style="color: #000000">{</br>
            @JoinColumn(name</span>="function_id"<span style="color: #000000">)})</br>
    </span><span style="color: #0000ff">private</span> List&lt;Function&gt; functionList=<span style="color: #0000ff">new</span> ArrayList&lt;&gt;<span style="color: #000000">();</br></br>
    
    @JsonBackReference</br>
    </span><span style="color: #0000ff">public</span> List&lt;Function&gt;<span style="color: #000000"> getFunctionList(){</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> functionList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> setFunctionList(List&lt;Function&gt;<span style="color: #000000"> functionList){</br>
        </span><span style="color: #0000ff">this</span>.functionList=<span style="color: #000000">functionList;</br>
    }</br></br>
    
    @JsonBackReference</br>
    </span><span style="color: #0000ff">public</span> List&lt;User&gt;<span style="color: #000000"> getUserList() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> userList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> setUserList(List&lt;User&gt;<span style="color: #000000"> userList) {</br>
        </span><span style="color: #0000ff">this</span>.userList =<span style="color: #000000"> userList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> Integer getRole_id() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> role_id;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setRole_id(Integer role_id) {</br>
        </span><span style="color: #0000ff">this</span>.role_id =<span style="color: #000000"> role_id;</br>
    }</br>
    
    
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getRole_name() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> role_name;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setRole_name(String role_name) {</br>
        </span><span style="color: #0000ff">this</span>.role_name =<span style="color: #000000"> role_name;</br>
    }</br>
    
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getRole_description() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> role_description;</br>
    }</br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setRole_description(String role_description) {</br>
        </span><span style="color: #0000ff">this</span>.role_description =<span style="color: #000000"> role_description;</br>
    }</br>
    

    }

    复制代码

      Function实体(权限):

    复制代码
    package com.cy.coo.bean;
    

    import java.util.List;

    import javax.persistence.Entity;

    import javax.persistence.GeneratedValue;

    import javax.persistence.Id;

    import javax.persistence.JoinColumn;

    import javax.persistence.JoinTable;

    import javax.persistence.ManyToMany;



    @Entity

    public class Function {

    @Id</br>
    @GeneratedValue</br>
    </span><span style="color: #0000ff">private</span> Integer function_id;<span style="color: #008000">//</span><span style="color: #008000">功能序号</span></br></br>
    
    <span style="color: #0000ff">private</span> String permission;<span style="color: #008000">//</span><span style="color: #008000">权限字符串</span>
    



    @ManyToMany</br>
    @JoinTable(name </span>= "Role_Function", joinColumns = { @JoinColumn(name = "function_id") }, inverseJoinColumns =<span style="color: #000000"> {</br>
            @JoinColumn(name </span>= "role_id"<span style="color: #000000">) })</br>
    </span><span style="color: #0000ff">private</span> List&lt;Role&gt;<span style="color: #000000"> roleList;</br></br>
    
    </span><span style="color: #0000ff">public</span> List&lt;Role&gt;<span style="color: #000000"> getRoleList() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> roleList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> setRoleList(List&lt;Role&gt;<span style="color: #000000"> roleList) {</br>
        </span><span style="color: #0000ff">this</span>.roleList =<span style="color: #000000"> roleList;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> Integer getFunction_id() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> function_id;</br>
    }</br></br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setFunction_id(Integer function_id) {</br>
        </span><span style="color: #0000ff">this</span>.function_id =<span style="color: #000000"> function_id;</br>
    }</br></br></br>
    
    
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getPermission() {</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> permission;</br>
    }</br>
    
    </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setPermission(String permission) {</br>
        </span><span style="color: #0000ff">this</span>.permission =<span style="color: #000000"> permission;</br>
    }</br>
    

    }

    复制代码

      这几个实体类的具体关系如下图,也完美的解释了为什么会生成5张表:

      三、写一个与前端交互的controller方法,service层的具体逻辑的方法

        @PostMapping(value = "/logon")
    public Object logon(@RequestBody Login user) {

        </span><span style="color: #0000ff">return</span><span style="color: #000000"> userService.login(user);</br>
    }</span></pre>
    

      这个方法就是将前端传来的username和password封装到Login类中,Login类也只有这两个属性,然后调用Service层的login方法来处理。下面是service的login方法:

    复制代码
    /**
         * 用户登录 create by yyc 2017年5月12日下午4:31:26
         */
    @Override
    public Object login(Login user) {
    String username
    = user.getUsername().trim();
    String password
    = user.getPassword().trim();

        </span><span style="color: #008000">//</span><span style="color: #008000"> 检查空值</span></br>
        <span style="color: #0000ff">if</span> (!<span style="color: #000000">CheckObjectField.CheckField(user)) {</br>
            </span><span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ResultException(CheckObjectField.FieldName + "为空!"<span style="color: #000000">);
        }</br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000"> 检查用户状态</span></br>
        Integer userState =<span style="color: #000000"> userRepository.findUserState(username);</br>
        </span><span style="color: #0000ff">if</span> (<span style="color: #0000ff">new</span> Integer("1"<span style="color: #000000">).equals(userState)) {</br>
            </span><span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ResultException("该用户已锁定"<span style="color: #000000">);</br>
        }</br></br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000"> 1、获取Subject实例对象</span></br>
        Subject currentUser =<span style="color: #000000"> SecurityUtils.getSubject();</br></br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000"> 2、判断当前用户是否登录</span></br>
        <span style="color: #0000ff">if</span> (currentUser.isAuthenticated() == <span style="color: #0000ff">false</span><span style="color: #000000">) {</br>
            </span><span style="color: #008000">//</span><span style="color: #008000"> 3、将用户名和密码封装到UsernamePasswordToken</span></br>
            UsernamePasswordToken token = <span style="color: #0000ff">new</span><span style="color: #000000"> UsernamePasswordToken(username, password);</br></br>
    
            </span><span style="color: #008000">//</span><span style="color: #008000"> 4、认证</span></br>
            <span style="color: #0000ff">try</span><span style="color: #000000"> {</br>
                currentUser.login(token);</span><span style="color: #008000">//</span><span style="color: #008000"> 传到MyAuthorizingRealm类中的方法进行认证</span></br>
                Session session =<span style="color: #000000"> currentUser.getSession();</br>
                session.setAttribute(</span>"username"<span style="color: #000000">, username);</br>
            } </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (AuthenticationException e) {</br>
                </span><span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ResultException("密码或用户名错误"<span style="color: #000000">);</br>
            }</br>
        }</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 根据用户名查询角色信息</span></br>
        List&lt;String&gt; RoleNames =<span style="color: #000000"> roleService.findRoleName(username);</br></br>
    
        </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span><span style="color: #000000"> LoginReturn(username, RoleNames);</br></br>
    
    }</span></pre>
    
    复制代码

      service中主要是将用户名和密码封装到shiro的UsernamePasswordToken中,然后将token对象放到SecurityUtils.getSubject()的login方法中,以便shiro认证登录使用。认证失败就会抛出AuthenticationException这个异常,就对异常进行相应的操作,这里的处理是抛出一个自定义异常ResultException。

      四、写我认为的shiro的核心类

    复制代码
    package com.cy.coo.shiro;
    

    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.authc.UsernamePasswordToken;

    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.apache.shiro.util.ByteSource;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import org.springframework.beans.factory.annotation.Autowired;

    import com.cy.coo.bean.Function;

    import com.cy.coo.bean.Role;

    import com.cy.coo.bean.User;

    import com.cy.coo.service.UserService;

    /**
    *
    *

    • @author E-mail:34782655@qq.com
    • @version 创建时间:2017年5月8日 上午10:50:50
    • 类说明:
    • --
      */

      public class MyAuthorizingRealm extends AuthorizingRealm {

    </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">final</span> <span style="color: #0000ff">static</span> Logger logger=LoggerFactory.getLogger(MyAuthorizingRealm.<span style="color: #0000ff">class</span><span style="color: #000000">);</br></br>
    
    @Autowired</br>
    </span><span style="color: #0000ff">private</span><span style="color: #000000"> UserService userService;</br>
    </span><span style="color: #008000">//</span><span style="color: #008000">shiro的权限配置方法</span></br>
    

    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        logger.info(</span>"权限配置--&gt;doGetAuthorizationInfo"<span style="color: #000000">);</br></br>
        
        SimpleAuthorizationInfo authorizationInfo </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> SimpleAuthorizationInfo();</br>
        logger.info(</span>"-----------------------------&gt;"+<span style="color: #000000">principals.getPrimaryPrincipal());</br>
        User user</span>=<span style="color: #000000">(User) principals.getPrimaryPrincipal();</br>
        </span><span style="color: #0000ff">for</span><span style="color: #000000">(Role role:user.getRoleList()){</br>
            authorizationInfo.addRole(role.getRole_name());</br>
            </span><span style="color: #0000ff">for</span><span style="color: #000000">(Function function:role.getFunctionList()){</br>
                authorizationInfo.addStringPermission(function.getPermission());</br>
            }</br>
        }</br></br>
        
        logger.info(</span>"用户"+user.getName()+"具有的角色:"+<span style="color: #000000">authorizationInfo.getRoles());</br>
        logger.info(</span>"用户"+user.getName()+"具有的权限:"+<span style="color: #000000">authorizationInfo.getStringPermissions());</br></br>
        
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> authorizationInfo;</br>
    }</br></br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000">shiro的身份验证方法</span></br>
    

    @Override

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        logger.info(</span>"正在验证身份..."<span style="color: #000000">);</br>
        SimpleAuthenticationInfo info</span>=<span style="color: #0000ff">null</span><span style="color: #000000">;</br></br>
        
        </span><span style="color: #008000">//</span><span style="color: #008000">将token转换成UsernamePasswordToken</span></br>
        UsernamePasswordToken upToken =<span style="color: #000000"> (UsernamePasswordToken) token;</br>
        </span><span style="color: #008000">//</span><span style="color: #008000">从转换后的token中获取用户名</span></br>
        String username=<span style="color: #000000"> upToken.getUsername();  </br>
        logger.info(</span>"-----&gt;"+<span style="color: #000000">username);</br></br>
        
        </span><span style="color: #008000">//</span><span style="color: #008000">查询数据库,得到用户</span></br>
        User user=<span style="color: #000000">userService.findByName(username);</br>
        </span><span style="color: #0000ff">if</span>(user==<span style="color: #0000ff">null</span><span style="color: #000000">){</br>
            </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span><span style="color: #000000">;</br>
        }</br></br>
        
        </span><span style="color: #008000">//</span><span style="color: #008000">得到加密密码的盐值</span></br>
        ByteSource salt =<span style="color: #000000"> ByteSource.Util.bytes(user.getSalt());</br>
    

    // logger.info("加密密码的盐:"+salt);

    // //得到盐值加密后的密码:只用于方便数据库测试,后期不会用到。

    // Object md = new SimpleHash("MD5",upToken.getPassword(),salt,1024);

    // logger.info("盐值加密后的密码:"+md);


    info
    = new SimpleAuthenticationInfo(

    user,
    //用户名

    user.getPassword(), //密码

    salt, //加密的盐值

    getName() //realm name

    );
    return info;

    }

    }

    复制代码

      这个类继承shiro的AuthorizingRealm ,主要有两个方法,一个是权限配置,一个是身份认证,权限配置:当我们要用到权限时shiro会回调doGetAuthorizationInfo这个方法,对当前的用户分配权限,这个方法中的嵌套for循环是怎么回事呢,其实就是将数据库中的对应角色、权限放进shiro中,让他来管理,这需要实体类User中有getRoleList()、getRole_name()和getFunctionList()、getPermission这几个方法,这几个个方法就是设计数据库和实体类时的东西了,关于shiro权限相关的实体类在前面已经给出了。身份认证:在用户登录认证的时候回调,认证失败就抛出AuthenticationException。

      五、shiro配置类

    复制代码
    package com.cy.coo.shiro;
    

    import java.util.LinkedHashMap;

    import java.util.Map;

    import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

    import org.apache.shiro.cache.ehcache.EhCacheManager;

    import org.apache.shiro.mgt.SecurityManager;

    import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;

    import org.apache.shiro.spring.web.ShiroFilterFactoryBean;

    import org.apache.shiro.web.mgt.CookieRememberMeManager;

    import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

    import org.apache.shiro.web.servlet.SimpleCookie;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

    import org.springframework.beans.factory.annotation.Qualifier;

    import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.core.io.ClassPathResource;

    @Configuration // 等价于beans

    public class ShiroConfig {

    </span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> Logger log = LoggerFactory.getLogger(ShiroFilterFactoryBean.<span style="color: #0000ff">class</span><span style="color: #000000">);</br></br>
    
    @Bean(name </span>= "securityManager"<span style="color: #000000">)</br>
    </span><span style="color: #0000ff">public</span> SecurityManager securityManager(@Qualifier("authRealm"<span style="color: #000000">) MyAuthorizingRealm authRealm,
            @Qualifier(</span>"cookieRememberMeManager"<span style="color: #000000">) CookieRememberMeManager cookieRememberMeManager) {</br>
        log.info(</span>"securityManager()"<span style="color: #000000">);</br>
        DefaultWebSecurityManager securityManager </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> DefaultWebSecurityManager();</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 设置realm.</span></br>
    

    securityManager.setRealm(authRealm);

        </span><span style="color: #008000">//</span><span style="color: #008000"> 设置rememberMe管理器</span></br>
    

    securityManager.setRememberMeManager(cookieRememberMeManager);

        </span><span style="color: #0000ff">return</span><span style="color: #000000"> securityManager;</br>
    }</br>
    
    </span><span style="color: #008000">/**</span><span style="color: #008000"></br>
     * realm</br>
     * </br>
     * </span><span style="color: #808080">@return</span></br>
     <span style="color: #008000">*/</span><span style="color: #000000"></br>
    @Bean(name </span>= "authRealm"<span style="color: #000000">)</br>
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> MyAuthorizingRealm myAuthRealm(</br>
            @Qualifier(</span>"hashedCredentialsMatcher"<span style="color: #000000">) HashedCredentialsMatcher matcher,</br>
            @Qualifier(</span>"ehCacheManager"<span style="color: #000000">) EhCacheManager  ehCacheManager) {</br>
        log.info(</span>"myShiroRealm()"<span style="color: #000000">);</br>
        MyAuthorizingRealm myAuthorizingRealm </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> MyAuthorizingRealm();</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 设置密码凭证匹配器</span></br>
        myAuthorizingRealm.setCredentialsMatcher(matcher); <span style="color: #008000">//</span><span style="color: #008000"> myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 设置缓存管理器</span></br>
    

    myAuthorizingRealm.setCacheManager(ehCacheManager);

        </span><span style="color: #0000ff">return</span><span style="color: #000000"> myAuthorizingRealm;</br>
    }</br>
    

        /**

    * 缓存管理器

    *
    @return

    */

    @Bean(value
    ="ehCacheManager")

    public EhCacheManager ehCacheManager(@Qualifier("ehCacheManagerFactoryBean") EhCacheManagerFactoryBean bean) {

    log.info(
    "ehCacheManager()");

    EhCacheManager cacheManager
    = new EhCacheManager();

    cacheManager.setCacheManagerConfigFile(
    "classpath:ehcache-shiro.xml");

    return cacheManager;

    }

    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * cookie对象;
     * 
     * </span><span style="color: #808080">@return</span></br>
     <span style="color: #008000">*/</span><span style="color: #000000"></br>
    @Bean</br>
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> SimpleCookie rememberMeCookie() {</br>
        log.info(</span>"rememberMeCookie()"<span style="color: #000000">);</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 这个参数是cookie的名称,对应前端的checkbox 的name = rememberMe</span></br>
        SimpleCookie simpleCookie = <span style="color: #0000ff">new</span> SimpleCookie("rememberMe"<span style="color: #000000">);</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> &lt;!-- 记住我cookie生效时间30天(259200) ,单位秒;--&gt;</span></br>
        simpleCookie.setMaxAge(259200<span style="color: #000000">);</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> simpleCookie;</br>
    }</br></br>
    
    </span><span style="color: #008000">/**</span><span style="color: #008000"></br>
     * 记住我管理器 cookie管理对象;</br>
     * </br>
     * </span><span style="color: #808080">@return</span></br>
     <span style="color: #008000">*/</span><span style="color: #000000"></br>
    @Bean(name </span>= "cookieRememberMeManager"<span style="color: #000000">)</br>
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> CookieRememberMeManager rememberMeManager() {</br>
        System.out.println(</span>"rememberMeManager()"<span style="color: #000000">);</br>
        CookieRememberMeManager cookieRememberMeManager </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> CookieRememberMeManager();</br>
        cookieRememberMeManager.setCookie(rememberMeCookie());</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> cookieRememberMeManager;</br>
    }</br></br>
    
    </span><span style="color: #008000">/**</span><span style="color: #008000"></br>
     * 密码匹配凭证管理器</br>
     * </br>
     * </span><span style="color: #808080">@return</span></br>
     <span style="color: #008000">*/</span><span style="color: #000000"></br>
    @Bean(name </span>= "hashedCredentialsMatcher"<span style="color: #000000">)</br>
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> HashedCredentialsMatcher hashedCredentialsMatcher() {</br>
        log.info(</span>"hashedCredentialsMatcher()"<span style="color: #000000">);</br>
        HashedCredentialsMatcher hashedCredentialsMatcher </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> HashedCredentialsMatcher();</br></br>
    
        hashedCredentialsMatcher.setHashAlgorithmName(</span>"MD5");<span style="color: #008000">//</span><span style="color: #008000"> 散列算法:这里使用MD5算法;</span></br>
        hashedCredentialsMatcher.setHashIterations(1024);<span style="color: #008000">//</span><span style="color: #008000"> 散列的次数,比如散列两次,相当于
                                                            </span><span style="color: #008000">//</span><span style="color: #008000"> md5(md5(""));</span></br></br>
    
        <span style="color: #0000ff">return</span><span style="color: #000000"> hashedCredentialsMatcher;</br></br>
    }
    
    </span><span style="color: #008000">/**</span><span style="color: #008000">
     * 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持; Controller才能使用@RequiresPermissions
     * 
     * </span><span style="color: #808080">@param</span><span style="color: #008000"> securityManager</br>
     * </span><span style="color: #808080">@return</span></br>
     <span style="color: #008000">*/</span><span style="color: #000000">
    @Bean
    </span><span style="color: #0000ff">public</span><span style="color: #000000"> AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(</br>
            @Qualifier(</span>"securityManager"<span style="color: #000000">) SecurityManager securityManager) {</br>
        log.info(</span>"authorizationAttributeSourceAdvisor()"<span style="color: #000000">);</br>
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> authorizationAttributeSourceAdvisor;</br>
    }</br>
    
    @Bean</br>
    </span><span style="color: #0000ff">public</span> ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager"<span style="color: #000000">) SecurityManager securityManager) {</br>
        log.info(</span>"shirFilter()"<span style="color: #000000">);</br>
        ShiroFilterFactoryBean shiroFilterFactoryBean </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> ShiroFilterFactoryBean();</br></br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000"> 必须设置 SecurityManager</span></br>
    

    shiroFilterFactoryBean.setSecurityManager(securityManager);

        </span><span style="color: #008000">//</span><span style="color: #008000"> 拦截器.</span></br>
        Map&lt;String, String&gt; map = <span style="color: #0000ff">new</span> LinkedHashMap&lt;String, String&gt;<span style="color: #000000">();</br></br>
    
        map.put(</span>"/logout", "logout"<span style="color: #000000">);</br>
        map.put(</span>"/login", "anon"<span style="color: #000000">);</br>
        map.put(</span>"/logon", "anon"<span style="color: #000000">);</br></br>
    
        map.put(</span>"/**", "authc"<span style="color: #000000">);</br></br>
    
        </span><span style="color: #008000">//</span><span style="color: #008000"> 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面</span></br>
        shiroFilterFactoryBean.setLoginUrl("/login"<span style="color: #000000">);</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 登录成功后要跳转的链接</span></br>
        shiroFilterFactoryBean.setSuccessUrl("/index"<span style="color: #000000">);</br>
        </span><span style="color: #008000">//</span><span style="color: #008000"> 未授权界面;</span></br>
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized"<span style="color: #000000">);</br></br>
    
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);</br>
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> shiroFilterFactoryBean;</br>
    }</br>
    

    }

    复制代码

      这个没什么好说的,最后一个类是shiro的过滤器配置。可以看到我在每个方法上面加了一个@Bean(name="..."),其实这是spring的注解,将这个类放到spring容器中管理,在方法形参中使用@Qualifier(...)来使用它,以致于我们在方法体中调用某个方法时就方面多了。

    在这里,关于shiro在springboot中的基础配置就完成了。下面是期间遇到的错误解决方案:

    错误一:关于实体类的错误,springboot 中hibernate懒加载  报错....................................No  Session
    解决方法:新建类 配置OpenEntityManagerInViewFilter    以及  上面角色类(表)和用户类(表)(Role、User)Role的红色字体也是必须的,及@ManyToMany(fetch=FetchType.EAGER)
    由于博主基础的局限还不知道具体的原因是什么,但是解决了就好。
    复制代码
    @Configuration
    public class HibernateConfig {
    @Bean
    public FilterRegistrationBean registerOpenEntityManagerInViewFilterBean() {
    FilterRegistrationBean registrationBean
    = new FilterRegistrationBean();
    OpenEntityManagerInViewFilter filter
    = new OpenEntityManagerInViewFilter();
    registrationBean.setFilter(filter);
    registrationBean.setOrder(
    5);
    return registrationBean;
    }
    }
    复制代码

    参考文章:

    http://stackoverflow.com/questions/33622222/spring-boot-opensessioninviewfilter-with-actuator-and-custom-security 

    http://www.jianshu.com/p/a827ecdda99f

    http://www.w_2bc.com/article/201653 /*这个链接博客园不让我发啊,把w_2_b_c中的下划线删了即可*/

    错误二:这个在前面也提到过了,返回json数据出现Could not write JSON document: Infinite recursion(无法编写JSON文档:无限递归 );

    在后面的使用中发现这个错误也是这样解决的,java.lang.IllegalStateException: Cannot call sendError() after the response has been committed,错误页面到最后就是这样,如图:

    解决方法:

      在controller返回数据到统一json转换的时候,出现了json infinite recursion stackoverflowerror的错误,即json在将对象转换为json格式的数据的时候,出现了无限递归调用的情况。
    具体的情况如下:
        A类中,有个属性:List<B> b, A与B的关系为 OneToMany;在B类中,有属性A a,引用到A中的字段id,并作为外键。hibernate查询结果正常,可以看到返回的A对象中,有b参数值,但在json转换的时候就出现了无限递归的情况。个人分析,应该是json在序列化A中的b属性的时候,找到了B类,然后序列化B类,而B类中有a属性,因此,为了序列化a属性,json又得去序列化A类,如此递归反复,造成该问题。
    解决:
        在B类中a的getter setter方法上加注解@JsonBackReference,其实自己试过只在getter方法上加@JsonBackReference也够了。
     
     
  • 相关阅读:
    微软经典项目实例
    Extjs在vs中使用及弹出对话框的介绍
    微软企业库5.0学习笔记(七)
    微软企业库5.0学习笔记(八)
    微软企业库5.0学习笔记(十)
    .NET 4 并行(多核)编程系列之五
    NET 应用架构指导 V2[12]
    .NET 4 并行(多核)编程系列之四
    .NET 4 并行(多核)编程系列之三
    微软企业库5.0学习笔记(十二)
  • 原文地址:https://www.cnblogs.com/jpfss/p/8377351.html
Copyright © 2020-2023  润新知