用springboot springsecurity mybatisplus写一个登录以及退出的权限设置 含有domain层 controller层 service层以及mapper层
时间: 2023-08-20 13:37:58 浏览: 165
好的,下面是一个简单的示例代码:
1. 首先,创建一个User实体类,用于存储用户信息
```java
package com.example.demo.domain;
import lombok.Data;
@Data
public class User {
private Long id;
private String username;
private String password;
private String role;
}
```
2. 创建一个UserMapper接口,用于操作数据库
```java
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
3. 创建一个UserService接口及其实现类,用于处理业务逻辑
```java
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.domain.User;
public interface UserService extends IService<User> {
User getUserByUsername(String username);
}
```
```java
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public User getUserByUsername(String username) {
return lambdaQuery().eq(User::getUsername, username).one();
}
}
```
4. 创建一个WebSecurityConfig类,用于配置Spring Security
```java
package com.example.demo.config;
import com.example.demo.handler.CustomAuthenticationFailureHandler;
import com.example.demo.handler.CustomAuthenticationSuccessHandler;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
@Autowired
private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
return username -> userService.getUserByUsername(username);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
5. 创建一个CustomAuthenticationSuccessHandler类和一个CustomAuthenticationFailureHandler类,用于处理登录成功和登录失败的逻辑
```java
package com.example.demo.handler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
request.getSession().setAttribute("username", userDetails.getUsername());
super.onAuthenticationSuccess(request, response, authentication);
}
}
```
```java
package com.example.demo.handler;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
response.sendRedirect("/login?error=1");
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
}
```
6. 创建一个UserController类,用于处理登录和退出的请求
```java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/logout")
public String logout() {
return "redirect:/";
}
}
```
7. 最后,创建一个login.html页面和一个index.html页面,用于展示登录和退出的效果
login.html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<p><label>Username:</label> <input type="text" name="username"></p>
<p><label>Password:</label> <input type="password" name="password"></p>
<p><input type="submit" value="Login"></p>
</form>
<c:if test="${param.error != null}">
<p style="color: red">Incorrect username or password.</p>
</c:if>
</body>
</html>
```
index.html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>Hello, ${sessionScope.username}!</h1>
<form action="/logout" method="post">
<p><input type="submit" value="Logout"></p>
</form>
</body>
</html>
```
以上就是一个简单的Spring Boot + Spring Security + MyBatis Plus的登录以及退出的权限设置示例代码。
阅读全文