Shiro elementui used before and after the end of separation and MyBatis

It is integrated in a single project: https: //www.cnblogs.com/xiaoruirui/p/11696318.html

login page

<template>
  <div class="login-container">
    <el-form :model="ruleForm2" :rules="rules2"
             status-icon
             ref="ruleForm2"
             label-position="left"
             label-width="0px"
             class="demo-ruleForm login-page">
      <H3 class = "title"> System Log </ h3>
      <el-form-item prop="username">
        <el-input type="username"
                  v-model="ruleForm2.username"
                  auto-complete="off"
                  placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password"
                  v-model="ruleForm2.password"
                  auto-complete="off"
                  placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-checkbox
              v-model="checked"
              class="rememberme"
      > Remember password </ el-checkbox>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click="handleSubmit" :loading="logining">登录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getWxLoginUrl">微信登陆</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
    export default {
        data(){
            return {
                addFormVisible: false ,
                logining: false ,
                ruleForm2: {
                    username: '',
                    password: '',
                },
                wxLoginUrl:"",
                rules2: {
                    username: [{required: true, message: 'please enter your account', trigger: 'blur'}],
                    password: [{required: true, message: 'enter your password', trigger: 'blur'}]
                },
                checked: false
            }
        },
        methods: {
            // This is the two-dimensional code obtained as a pale channel 
            getWxLoginUrl (Event) {
                 the this . Http.get $ ( '/ Login'). The then ((RES) => {
                    console.debug(res) ;
                    let { msg, success,wxLoginUrl, resultObj } = res.data;
                    if (!success) {
                        this.$message({
                            message: msg,
                            type: 'error'
                        });
                    } The else {
                         // jump page this way
                        // . Router.push the this $ ({path: '/ wxLoginUrl'}); 
                        window.location.href = wxLoginUrl
                    }
                })
            },
            // ordinary landing 
            handleSubmit (event) {
                _this var = the this ;
                 the this $ refs.ruleForm2.validate ((Valid) =>. {
                     IF (Valid) {
                         the this .logining = to true ;
                         // set the parameter into the transmission request determines whether a parameter database 
                        var loginParams = { username: the this .ruleForm2.username, password: the this .ruleForm2.password};
                         // equestLogin (loginParams) .then (Data => { 
                        the this $ http.post ( '/ Login', loginParams) .then (Data =>. {
                             the this .logining =false;
                            console.debug(data);
                            // get the return value of 
                            the let {MSG, Success, for resultObj} = data.data;
                             IF (! Success) {
                                 the this $ Message ({.
                                    message: msg,
                                    type: 'error'
                                });
                            } The else {
                                 // successful login session bind data to be used the next login 
                                sessionStorage.setItem ( 'User' , the JSON.stringify (resultObj.user.username));
                                sessionStorage.setItem ( 'token' , resultObj.token);
                                 // jump to page 
                                the this $ router.push ({path: '/ echarts'. });
                            }
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    };
</script>

<style scoped>
  .login-container {
    width: 100%;
    height: 100%;
  }
  .login-page {
    -webkit-border-radius: 5px;
    border-radius: 5px;
    margin: 180px auto;
    width: 350px;
    padding: 35px 35px 15px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }
  label.el-checkbox.rememberme {
    margin: 0px 0px 15px;
    text-align: left;
  }
</style>
View Code

 

In main.js need to release path

router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

 

Here is the LoginController request sent by landing

@RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResoult login(@RequestBody Employee employee){
        The currentUser the Subject = SecurityUtils.getSubject ();
             // get the token pass parameters to determine whether the correct 
        IF (! CurrentUser.isAuthenticated ()) {
             the try {
                Token MyUsernamePasswordToken = new new MyUsernamePasswordToken (employee.getUsername (), employee.getPassword ());
                 // current user is added via line 
                currentUser.login (token);
                 // not here return 
                / * return a JsonResult new new (); * / 
            } the catch (UnknownAccountException E) {
                 // determines whether an error username 
                e.printStackTrace ();
                System.out.println ( "Please enter a correct user name" );
                 return  new new AjaxResoult () setMsg ( "user name or password is incorrect" + e.getMessage ()) setSuccess (.. False );
            } The catch (IncorrectCredentialsException E) {
                 // determines whether the password is wrong 
                e.printStackTrace ();
                System.out.println ( "Please enter the correct password is" );
                 return  new new AjaxResoult () setMsg ( "user name or password is incorrect" + e.getMessage ()) setSuccess (.. False );
            } The catch (of AuthenticationException E) {
                 // all errors 
                e.printStackTrace ();
                System.out.println ( "Error Unknown" );
                 return  new new AjaxResoult () setMsg ( "system error" + e.getMessage ()) setSuccess (.. To false );
            }
        }
        Employee employee1 = (Employee) currentUser.getPrincipal();
        employee.setPassword(null);
        AjaxResoult AjaxResoult = new new AjaxResoult ();
         // get sessionId 
        the Map <String, Object> the Result = new new HashMap <> ();
         // In addition to returning the login is successful or not, but also to return to the front end user login 
        result.put ( "user " , employee1);
        result.put("token",currentUser.getSession().getId());
        ajaxResoult.setResultObj (result);
        return ajaxResoult;
    }
View Code

 

Because the service before and after the station sent a request to determine whether it is necessary to vary Yang landed

Needs to be used to determine a class override DefaultWebSessionManager

Package Cn.Jiedada.Crm.Web.Shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 *
 * Traditional construction projects, shiro sessionId read from the cookie in order to maintain the session,
 * (APP can also be used in a mobile item) separating the rear end of the previous project, we choose to pass ajax sessionId in the request header,
 * Shiro way to get it is necessary to rewrite the sessionId.
 * Custom CrmSessionManager class inherits DefaultWebSessionManager class, override the method getSessionId
 *
 */
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);
        REQUEST1 the HttpServletRequest = (the HttpServletRequest) Request;
         // If the request header has a value of 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;
        } The else {
             // otherwise by default rule taken from the cookie sessionId 
            return  Super .getSessionId (Request, Response);
        }
    }

}
View Code

 Add in the application

   <-! Session manager by extending our session DefaultWebSecurityManager customize ->
    <bean id="crmSessionManager" class="cn.jiedada.crm.web.shiro.CrmSessionManager"></bean>
    <-! Shiro core object ->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <! - Configure realm ->
        <property name="sessionManager" ref="crmSessionManager"/>
        <property name="realm" ref="myRealm"/>
    </bean>

 

Password matcher

MD5Util

Package Cn.Jiedada.Crm.Web.Shiro;

import org.apache.shiro.crypto.hash.SimpleHash;

public  class MD5Util {

    public static final String SALT = "jiedada";

    /**
     * Encryption
     * @param source
     * @return
     */
    public static String encrypt(String source){
        SimpleHash simpleHash = new SimpleHash("MD5",source,SALT,10);
        return simpleHash.toString();
    }

    public static void main(String[] args) {

        System.out.println(encrypt("123456"));
    }

}
View Code

 

Package Cn.Jiedada.Crm.Web.Shiro;

import cn.jiedada.crm.domain.Permission;
import cn.jiedada.crm.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Is used to return the following values ​​(the value here is in order: LinkedHashMap)
 *   <value>
         /login = anon
         /s/permission.jsp = perms[user:index]
         /** = authc
    </value>
 * / 
Public  Class ShiroFilterMapFactory {
    @Autowired
    private IPermissionService permissionService;
    public Map<String,String> createMap(){
        Map <String, String> Map = new new a LinkedHashMap <> ();
         // anon: clearance path required 
        map.put ( "/ Login", "anon" );
        map.put("/login","anon");
        map.put("*.js","anon");
        map.put("*.css","anon");
        map.put("/css/**","anon");
        map.put("/js/**","anon");
        map.put("/images/**","anon");
        //perms:权限拦截
        List<Permission> permissions = permissionService.findAll();
        permissions.forEach(p->{
            map.put(p.getUrl(),"aisellPers["+p.getSn()+"]");
        });
        //authc:拦截
        map.put("/**","myFilter");
        return map;
    }
}
View Code

 

The key is through user permissions query methods in the mapper I wrote a method

 <-! Right found by employees ->
    <select id="findPermissionByEmployee" parameterType="long" resultType="permission">
        SELECT DISTINCT p.*
            from t_employee e
            JOIN t_department d
            ON e.department_id=d.id
            JOIN t_department_role dr
            on dr.department_id=d.id
            JOIN t_role_permission rp
            on dr.role_id=rp.role_id
            JOIN t_permission p
            on p.id=rp.permission_id
            where e.id=#{id}
    </select>

By department staff to find, to find role id-many, many-to-find and then find through role id id rights, privileges found

Because when elementui send axious whether it will fill the request to release the request so by the need to write a filter to send an options perspective

FormAuthenticationFilter

Package Cn.Jiedada.Crm.Web.Shiro;

import cn.jiedada.crm.web.wechart.LoginType;
import cn.jiedada.crm.web.wechart.MyUsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Custom authentication filter
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //如果是OPTIONS请求,直接放行
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String method = httpServletRequest.getMethod();
        //判断是否是OPTIONS请求
        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);
        LoginType String = LoginType.PASSWORD; // password is required

        if(request.getParameter("loginType")!=null && !"".equals(request.getParameter("loginType").trim())){
            loginType = request.getParameter("loginType");
        }

        return new MyUsernamePasswordToken(username, password,loginType,rememberMe,host);
    }
}
View Code

 

 Therefore, in the application-shiro

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <-! Session manager by extending our session DefaultWebSecurityManager customize ->
    <bean id="crmSessionManager" class="cn.jiedada.crm.web.shiro.CrmSessionManager"></bean>
    <-! Shiro core object ->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <! - Configure realm ->
        <property name="sessionManager" ref="crmSessionManager"/>
        <property name="realm" ref="myRealm"/>
    </bean>


    <!--Realms-->
    <bean id="myRealm" class="cn.jiedada.crm.web.shiro.MyRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="MD5"/>
                <property name="hashIterations" value="10"/>
            </bean>
        </property>
    </bean>
    <! - Custom filter ->
    <bean id="myAuthenticationFilter" class="cn.jiedada.crm.web.shiro.MyAuthenticationFilter"></bean>
    <bean id="aisellPermissionsAuthorizationFilter" class="cn.jiedada.crm.web.shiro.AisellPermissionsAuthorizationFilter"></bean>
    <-! Shiro filter configuration ->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <property name="successUrl" value="/s/index"/>
        <property name="unauthorizedUrl" value="/s/unauthorized"/>
        <! - found via key below what we need, requires the use of value-ref association ->
        <property name="filters">
            <map>
                <entry key="myFilter" value-ref="myAuthenticationFilter"></entry>
                <entry key="aisellPers" value-ref="aisellPermissionsAuthorizationFilter"></entry>
            </map>
        </property>
        <! - Use our myFilter down here ->
        <property name="filterChainDefinitions">
            <value>
                /* = anon
                /js/** = anon
                /** = myFilter
            </value>
        </property>
    </bean>



</beans>

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/xiaoruirui/p/11878128.html