springboot+vue3 用session机制,实现登录验证。

后端

  1. 创建Spring Boot项目:使用Spring Initializr创建一个Spring Boot项目,选择依赖Spring WebSpring Session.

  2. 添加依赖
    pom.xml中,添加Spring Session和Spring Security依赖:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 配置Redis
    application.properties中添加Redis配置:
spring.redis.host=localhost
spring.redis.port=6379
spring.session.store-type=redis
  1. 创建用户认证配置类
    创建一个类SecurityConfig来配置Spring Security:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/login", "/api/register").permitAll()
                .anyRequest().authenticated()
                .and()
            .csrf().disable()
            .formLogin()
                .loginProcessingUrl("/api/login")
                .defaultSuccessUrl("/home", true)
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/api/logout")
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
  1. 创建用户服务类
    创建一个类UserService来管理用户:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    private Map<String, String> users = new HashMap<>();

    public void register(String username, String password) {
        users.put(username, passwordEncoder.encode(password));
    }

    public boolean authenticate(String username, String password) {
        String encodedPassword = users.get(username);
        return encodedPassword != null && passwordEncoder.matches(password, encodedPassword);
    }
}
  1. 创建控制器类
    创建一个控制器类AuthController来处理登录和注册请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> response = new HashMap<>();
        if (userService.authenticate(username, password)) {
            response.put("status", "success");
        } else {
            response.put("status", "error");
            response.put("message", "Invalid username or password");
        }
        return response;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestParam String username, @RequestParam String password) {
        userService.register(username, password);
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        return response;
    }

    @GetMapping("/home")
    public Map<String, Object> home(Authentication authentication) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Welcome " + authentication.getName());
        return response;
    }
}

前端

  1. 创建Vue 3项目
    使用Vue CLI创建一个新的Vue 3项目:
vue create frontend
  1. 安装Axios
    在Vue项目根目录下安装Axios用于发送HTTP请求:
npm install axios
  1. 创建登录和注册页面
  • Login.vue:
<template>
  <div>
    <h1>Login</h1>
    <form @submit.prevent="login">
      <div>
        <label>Username:</label>
        <input v-model="username" type="text" required/>
      </div>
      <div>
        <label>Password:</label>
        <input v-model="password" type="password" required/>
      </div>
      <div>
        <button type="submit">Login</button>
      </div>
    </form>
    <div v-if="error">{{ error }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      error: ''
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/api/login', {
          username: this.username,
          password: this.password
        });
        if (response.data.status === 'success') {
          this.$router.push('/home');
        } else {
          this.error = response.data.message;
        }
      } catch (e) {
        this.error = 'An error occurred';
      }
    }
  }
};
</script>
  • Register.vue:
<template>
  <div>
    <h1>Register</h1>
    <form @submit.prevent="register">
      <div>
        <label>Username:</label>
        <input v-model="username" type="text" required/>
      </div>
      <div>
        <label>Password:</label>
        <input v-model="password" type="password" required/>
      </div>
      <div>
        <button type="submit">Register</button>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    async register() {
      try {
        const response = await axios.post('/api/register', {
          username: this.username,
          password: this.password
        });
        if (response.data.status === 'success') {
          this.$router.push('/login');
        }
      } catch (e) {
        console.error(e);
      }
    }
  }
};
</script>
  • Home.vue:
<template>
  <div>
    <h1>Welcome Home</h1>
    <button @click="logout">Logout</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async logout() {
      try {
        await axios.post('/api/logout');
        this.$router.push('/login');
      } catch (e) {
        console.error(e);
      }
    }
  }
};
</script>
  1. 配置路由
    src/router/index.js中配置路由:
import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import Home from '../views/Home.vue';

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/home', component: Home },
  { path: '/', redirect: '/login' }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;
  1. 启动前后端
  • 启动Spring Boot应用:
./mvnw spring-boot:run
  • 启动Vue开发服务器:
npm run serve

这样,你就可以使用Vue 3来处理前端登录和注册界面,并通过Spring Boot后端进行登录验证。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天进步2015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值