下面我将详细讲解“springboot整合security和vue的实践”的完整攻略。
准备工作
首先我们需要准备好以下工具和软件:
- Java JDK 1.8 或以上版本
- Maven 3.0 或以上版本
- Vue CLI
- Node.js
创建Spring Boot项目
- 在intelliJ IDEA中创建一个新的Spring Boot项目
- 在pom.xml中添加Spring Security和其他必要的依赖项,例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 创建一个空的Security配置类(例如:SecurityConfig.java),并配置身份认证和授权
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
创建RESTful API
在创建RESTful API之前,我们需要在项目中添加Spring MVC依赖项。在pom.xml文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
然后,在项目中创建RESTful API和服务接口,并在config类中添加跨域配置,例如:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}
创建前端应用
- 用Vue CLI创建新的Vue项目:
vue create vue-example
- 在项目中安装axios和vue-router等所需要的依赖项:
npm install axios vue-router --save
- 创建一个路由文件(例如:routes.js)并配置路由:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
component: Login
}
]
})
- 创建一个组件文件(例如:Login.vue)来处理登录逻辑:
<template>
<div>
<h1>Login</h1>
<form @submit.prevent="login">
<label>Username:</label>
<input type="text" v-model="username">
<label>Password:</label>
<input type="password" v-model="password">
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login () {
axios.post('/api/login', {
username: this.username,
password: this.password
})
.then(response => {
console.log(response.data)
this.$router.push('/')
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
整合前后端项目
- 在Spring Boot项目中,添加一个登录处理器和一个登录验证过滤器:
public class CustomLoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
try {
Map<String, String> loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String username = loginData.get("username");
String password = loginData.get("password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
return this.getAuthenticationManager().authenticate(token);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
return super.attemptAuthentication(request, response);
}
}
}
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
if ("user".equals(username) && "password".equals(password)) {
return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
} else {
throw new BadCredentialsException("Authentication failed.");
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
- 在Security配置类中,配置登录过滤器和验证提供者:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.addFilterAt(new CustomLoginFilter("/api/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new CustomAuthenticationProvider());
}
}
- 在前端项目中,调用后端登录API进行长轮询登录。
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login () {
axios.post('/api/login', {
username: this.username,
password: this.password
})
.then(response => {
console.log(response.data)
// 登录成功后将Token存储在LocalStorage中,并跳转到主页面
localStorage.setItem(ACCESS_TOKEN, response.data.token)
this.$router.push('/')
})
.catch(error => {
console.log(error)
})
}
}
}
以上就是整个“Spring Boot整合Security和Vue的实践”的完整攻略,其中包含了创建Spring Boot和Vue项目,创建RESTful API和服务接口,以及整合前后端项目的完整步骤和示例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:springboot整合security和vue的实践 - Python技术站