spring boot + shiro + vue 登录

目录

参考

axios使用

axios安装

axios请求使用

axios拦截器

springboot前后端分离

vue前端

项目目录结构

修改主配置参数

添加控制页面

修改路由配置

Spring boot后端

项目目录结构

添加跨域拦截器

配置拦截

登录方法

获取用户信息

访问测试


参考

spring boot 整合shiro 登录参考:spring boot 整合mybatis 和 shiro 实现登录

axios使用

基于promise用于浏览器和node.js的http客户端

axios安装

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios请求使用

执行 GET 请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios拦截器

在请求或响应被 then 或 catch 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

springboot前后端分离

vue前端

项目目录结构

修改主配置参数

在main.js中引入

import axios from 'axios'  // 一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端

import qs from 'qs'

设置为全局变量

Vue.prototype.$axios=axios
Vue.prototype.qs = qs

设置跨域默认请求地址

axios.defaults.baseURL = "http://localhost:8081/"     //配置默认发送请求到http://127.0.0.1:8081/

设置http拦截器

// http request 拦截器
axios.interceptors.request.use(
  function (config) {
    if (!window.sessionStorage.getItem('token')) {
      // console.log('>>>>> ' + router.currentRoute.fullPath)
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}
      })
    } else {
      console.log(window.sessionStorage.getItem('token'))
      config.headers.Authorization = window.sessionStorage.getItem('token')
    }
    console.log(config)
    return config;
  }, function (error) {
    return Promise.reject(error);
  })

// http response 拦截器
axios.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    if (error.response) {
      if (error.response.status == 401) {
        sessionStorage.removeItem('token')
        router.replace({
          href: '/login',
          query: {redirect: router.currentRoute.fullPath}
        })
      } else {
        next()
      }
      return Promise.reject(error.response.data)  // 返回接口返回的错误信息
    }
  })

 设置url拦截器

// url 拦截
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    sessionStorage.removeItem('token');
  }
  let user = sessionStorage.getItem('user');
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else if(user && to.path != '/login' && to.path != '/404' && to.path != '/'){
    let allow = false
    if(to.path === '/hello'){
      allow = true
    }
    if (allow) {
      console.log('有权限进入' + to.path);
      next()
    } else {
      console.log('没有权限进入' + to.path);
      next({ path: '/404' })
    }
  } else {
    next()
  }
})

添加控制页面

在components中新建Login.vue

<template>
  <div id="login">
    <form>
      <label for="userName">用户名</label><input type="text" v-model="userName" name="userName" />
      <label for="password">密码</label><input type="password" v-model="password" name="password"/>
      <input type="button" value="登录" @click="doLogin"/>
    </form>
  </div>
</template>


<script>
  import qs from 'qs'
  export default {
    name: 'login',
    data () {
      return {
        userName: '',
        password: ''
      }
    },
    methods:{
      doLogin () {   //登录提交方法
        this.$axios.post('/login',
          qs.stringify({
            userName: this.userName,
            password: this.password,
          })
        )
          .then((response) => {
            console.log(response)
            sessionStorage.setItem('user', qs.stringify(response.data.result));
            sessionStorage.setItem('token', response.data.token);
            this.$router.replace({path: '/hello'})
         })
      }
    }
  }
</script>

编辑HelloWorld.vue 页面

<template>
  <div>
    <div class="hello">
      <button @click="sayOut">渲染</button>
    </div>
    <div>用户管理</div>
    <tr >
      <th>用户名</th>
      <th>年龄</th>
    </tr>
    <tr >
      <td>{{userName}}</td>
      <td>{{password}}</td>
    </tr>
  </div>
</template>


<script>
  export default {
    name: 'hello',
    data () {
      return {
        userName:'',
        password:''
      }
    },
    methods:{
      sayOut () {
        this.$axios.post('/user/userData')
          .then((response) => {
            this.userName = response.data.userName;
            this.password = response.data.password;
            console.log(response.data);
          }).catch(err => {
          console.log(err);
        })
      }
    }
  }

</script>

添加404页面

<template>
    <p class="page-container">404 page not found</p>
</template>

<style>
    .page-container {
        font-size: 40px;
        margin: 50px auto;
        text-align: center;
        color: rgb(192, 204, 218);
    }
    .page-container:hover {
        color: #f71833
    }
</style>

修改路由配置

修改router下的index.js

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/HelloWorld'
import Login from '@/components/Login'
import NotFound from '@/components/404'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/login',
      component: Login,
      name: '',
      hidden: true
    },
    {
      path: '/404',
      component: NotFound,
      name: '',
      hidden: true
    },
    {
      path: '/hello',
      component: Hello,
      name: '',
      hidden: true
    }
  ]
})

Spring boot后端

项目目录结构

添加跨域拦截器

创建设置拦截器,在config目录下新建CorsConfig.java
 


@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 配置所有请求
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}

配置拦截

SpringBoot实现WebMvcConfigurer接口做一些配置拦截

package cn.ac.sec.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {
//extends WebMvcConfigurationSupport {   //后期要集成swagger,继承WebMvcConfigurationSupport会出现加载不了swagger的静态文件问题

	@Bean
    public LoginInterceptor getLoginInterceptor() {
        return new LoginInterceptor();
    }
    
	public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getLoginInterceptor());
        
        // 排除配置
        //addInterceptor.excludePathPatterns("/**");
        //addInterceptor.excludePathPatterns("/login**");

        // 拦截配置
        //addInterceptor.addPathPatterns("/**");
        addInterceptor.addPathPatterns("/user/**");
    }

}

添加一个Interceptor,作为测试


public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
			return true;

	}

}

登录方法

稍微修改一下之前的登录接口。主要修改返回值以及返回类容

@PostMapping("/login")
    public Map<String, Object> login(HttpServletRequest request) {
		String loginName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.err.println(loginName+"=="+password);
		Map<String, Object> map = new HashMap<>();
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
		if (StringUtils.isNotEmpty(loginName) && StringUtils.isNotEmpty(password)) {
			try{
				subject.login(token);
				User user = (User)subject.getPrincipal();	
				subject.getSession().setAttribute("DT_LOGIN_USER", user);
				map.put("result", user);
				map.put("token", subject.getSession().getId());
			}catch(Exception ex){
				map.put("result", "fail");
			}
		} else {
			map.put("result", "fail");
		}
		return map;
    }

获取用户信息

添加UserController.java,用于登录成功后跳转获取用户信息测试

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@PostMapping("/userData")
	public String demo() {
		User user = userService.getUserByUserName("admin");
		return JSON.toJSONString(user);
	}
	
}

访问测试

浏览器访问http://localhost:8080/#/login

访问成功跳转

点击渲染显示数据

项目代码:https://gitee.com/yetaot/springBootDemo

 

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue是一种现代化的JavaScript框架,用于构建用户界面。Element UI是基于Vue的组件库,提供了丰富的界面组件,方便开发者进行界面设计和开发。Spring Boot是一个快速开发Java应用的框架,可以轻松地创建独立的、基于Spring的应用程序。Shiro是一个强大且易于使用的Java安全框架,可用于身份验证、授权、加密和会话管理等。 结合Vue、Element UI、Spring BootShiro,可以实现权限到按钮的控制。首先,在Vue和Element UI中,可以根据当前用户的权限动态显示或隐藏按钮。在Vue组件中,根据后端返回的权限信息,可以通过v-if或v-show等指令来控制按钮的显示或隐藏。例如,只有具有特定权限的用户才能看到或操作某个按钮。 其次,在后端使用Spring BootShiro,可以进行更细粒度的权限控制。通过在后端创建角色和权限的映射关系,并根据用户的角色信息进行权限验证,可以确保只有具有相应权限的用户才能执行特定的操作。在需要进行权限验证的后端接口上,可以使用Shiro提供的注解来进行权限控制。例如,在Controller方法上添加@RequiresRoles注解,只允许拥有指定角色的用户调用该接口。 综上所述,通过结合Vue、Element UI、Spring BootShiro,可以实现权限到按钮的控制。在前端Vue和Element UI中,根据用户的权限信息来显示或隐藏按钮;在后端Spring BootShiro中,根据角色和权限的映射关系进行权限验证,确保只有具有相应权限的用户才能执行特定的操作。这种权限控制的方式可以提高系统的安全性和用户体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值