基于SpringSecurity的登录(SpringSecurity+Vue+ElementUI+axios前后端分离)
    		       		warning:
    		            这篇文章距离上次修改已过453天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简化的Spring Security登录功能的示例,使用Vue.js, Element UI和axios实现前后端分离。
后端(Spring Boot):
@RestController
@RequestMapping("/api/auth")
public class AuthController {
 
    @Autowired
    private AuthenticationManager authenticationManager;
 
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return ResponseEntity.ok("Login successful");
        } catch (AuthenticationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
    }
}
 
public class LoginRequest {
    private String username;
    private String password;
 
    // Getters and Setters
}前端(Vue.js):
<template>
  <el-form ref="loginForm" :model="loginForm" label-width="120px">
    <el-form-item label="Username">
      <el-input v-model="loginForm.username" name="username"></el-input>
    </el-form-item>
    <el-form-item label="Password">
      <el-input type="password" v-model="loginForm.password" name="password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="login">Login</el-button>
    </el-form-item>
  </el-form>
</template>
 
<script>
import axios from 'axios';
 
export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      }
    };
  },
  methods: {
    login() {
      axios.post('/api/auth/login', this.loginForm)
        .then(response => {
          console.log(response.data);
          // 登录成功后的处理逻辑,例如保存JWT
        })
        .catch(error => {
          console.error('Login failed', error.response.data);
          // 登录失败后的处理逻辑
        });
    }
  }
};
</script>确保你的Spring Security配置正确,并且Vue.js项目已经配置了axios以发送HTTP请求。这个例子只是一个简单的展示如何实现登录功能的参考,你需要根据自己的项目需求进行相应的安全配置和错误处理。
评论已关闭