springboot vue前后端分离 security 自定义登录
时间: 2023-08-22 07:09:28 浏览: 115
好的,我来简单介绍一下Spring Boot和Vue前后端分离中使用Security进行自定义登录的步骤。
首先,我们需要在Spring Boot中引入Spring Security依赖。可以在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,我们需要创建一个类来实现SecurityConfigurerAdapter,并重写configure方法。在这个方法中,我们可以自定义登录页面、登录接口、认证方式等等。以下是一个简单的例子:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/home")
.and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在上面的代码中,我们使用了一个自定义的UserService来获取用户信息,并使用BCryptPasswordEncoder对密码进行加密。
接下来,我们需要在Vue中发送登录请求,并将输入的用户名和密码传递给后端进行认证。可以使用axios库来发送请求。以下是一个简单的例子:
```javascript
axios.post('/login', {
username: 'user',
password: 'password'
}).then(response => {
// 登录成功,获取返回的token并保存到本地
const token = response.data.token;
localStorage.setItem('token', token);
}).catch(error => {
// 登录失败,输出错误信息
console.error(error.response.data);
});
```
在上面的代码中,我们发送了一个POST请求到/login接口,参数为username和password。如果登录成功,后端会返回一个token,我们将其保存到本地。如果登录失败,后端会返回一个错误信息,我们将其输出到控制台。
最后,我们需要在后端中验证token。可以在每个接口中添加一个拦截器,在拦截器中进行token的验证。以下是一个简单的例子:
```java
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从请求头中获取token
String token = request.getHeader("Authorization");
if (token == null) {
throw new UnauthorizedException("未登录");
}
// 验证token
String username = JwtUtil.getUsername(token);
User user = userService.loadUserByUsername(username);
if (!JwtUtil.verify(token, username, user.getPassword())) {
throw new UnauthorizedException("无效的token");
}
return true;
}
}
```
在上面的代码中,我们从请求头中获取token,并使用JwtUtil对token进行验证。如果验证通过,就说明用户已经登录。如果验证失败,就说明token无效,需要重新登录。
以上就是Spring Boot和Vue前后端分离中使用Security进行自定义登录的步骤。希望能对你有所帮助。
阅读全文
相关推荐
















