下面我将为您详细讲解“springSecurity实现简单的登录功能”的完整攻略。
1. 添加依赖
Spring Security是Spring的一个子项目,我们只需要在pom.xml文件中添加以下依赖即可:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.4.6</version>
</dependency>
2. 配置Spring Security
在Spring Security的配置类中,我们需要做以下几个步骤:
2.1 配置WebSecurity
通过继承WebSecurityConfigurerAdapter并重写configure方法,配置HttpSecurity和AuthenticationManagerBuilder。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService; // 用户信息Service
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll() // 放行登录请求
.anyRequest().authenticated() // 其他请求需要认证
.and()
.formLogin()
.loginPage("/login") // 指定登录页面URL
.defaultSuccessUrl("/index") // 登录成功后重定向的URL
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login") // 退出登录后重定向的URL
.permitAll();
}
/**
* 配置UserDetailsService和密码加密算法
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
2.2 配置UserDetailsService
我们需要自定义一个UserDetailsService,用于加载用户信息到Spring Security中。在实现UserDetailsService接口的loadUserByUsername方法中,根据用户名返回相应的用户信息。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService; // 用户信息Service
/**
* 根据用户名获取用户信息
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
authorities);
}
}
2.3 配置密码加密算法
配置BCryptPasswordEncoder作为密码加密算法。在configure方法中进行配置。
.passwordEncoder(new BCryptPasswordEncoder())
3. 创建登录页面
在视图中创建一个登录页面login.html,用于输入用户名和密码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
<form action="/login" method="POST">
<table>
<tr>
<td><label for="username">用户名:</label></td>
<td><input type="text" id="username" name="username"></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><button type="submit">登录</button></td>
</tr>
</table>
</form>
</body>
</html>
4. 创建登录后的页面
在视图中创建一个登录后的页面index.html,用于展示登录成功的信息。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>登录成功</h1>
<p>欢迎您,${username}</p>
<a href="/logout">退出登录</a>
</body>
</html>
5. 创建控制器
创建一个控制器UserController,用于处理登录和退出登录的请求。
@Controller
public class UserController {
@GetMapping({ "/", "/login" })
public String login() {
return "login";
}
@GetMapping("/index")
public String index(Model model) {
// 获取登录用户的信息
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
model.addAttribute("username", username);
}
return "index";
}
}
示例一
以下是一个基于示例的Spring Boot应用程序:
- 在pom.xml文件中添加相关依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.4.6</version>
</dependency>
- 创建WebSecurityConfig类。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
- 创建UserDetailsServiceImpl类。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
authorities);
}
}
- 创建UserController类。
@Controller
public class UserController {
@GetMapping({ "/", "/login" })
public String login() {
return "login";
}
@GetMapping("/index")
public String index(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
model.addAttribute("username", username);
}
return "index";
}
}
-
创建login.html和index.html模版。
-
运行应用程序并访问http://localhost:8080/login。
示例二
下面是一个基于示例的Spring MVC应用程序:
- 在pom.xml文件中添加相关依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.4.6</version>
</dependency>
- 配置Spring Security
创建WebSecurityConfig,配置HttpSecurity和AuthenticationManagerBuilder。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
- 创建UserDetailsServiceImpl类。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
authorities);
}
}
- 创建UserController类。
@Controller
public class UserController {
@GetMapping({ "/", "/login" })
public String login() {
return "login";
}
@GetMapping("/index")
public String index(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
model.addAttribute("username", username);
}
return "index";
}
}
-
创建login.jsp和index.jsp。
-
运行应用程序并访问http://localhost:8080/login.jsp。
以上就是Spring Security实现简单的登录功能的完整攻略,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:springSecurity实现简单的登录功能 - Python技术站