以下是关于SpringBoot security安全认证登录的实现方法的完整攻略,包含详细步骤、示例和代码:
SpringBoot security安全认证登录的实现方法
概述
在网站或应用程序中,用户登录是非常常见的一种操作。而用户登录操作需要进行安全认证,防止非法用户的登录,保障网站或应用的安全。SpringBoot提供了基于Spring Security的安全认证框架,通过基本配置以及简单的注解就可以实现登录认证的功能。
实现步骤
下面是实现SpringBoot security安全认证登录的步骤:
- 在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 创建一个SecurityConfig类并初始化
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
-
自定义UserDetailsService以及UserDetails
-
通过继承UserDetailsService接口,在其中实现loadUserByUsername方法来完成用户信息的查询。返回的UserDetails包含用户账号,密码以及角色/权限信息。
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
- 自定义UserDetails
public class CustomUserDetails implements UserDetails {
private User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<Role> roles = user.getRoles();
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
Set<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) {
authorities.add(new SimpleGrantedAuthority(permission.getName()));
}
}
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
- 创建登录页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页</title>
</head>
<body>
<h1>登录</h1>
<form name="loginForm" action="/login" method="POST">
<label>用户名:</label><input type="text" name="username"/><br/>
<label>密码:</label><input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
这里的form action为“/login”是Spring Security提供的默认登录校验地址,同时在这个页面的表单里,需要提交的参数名称必须是username和password。
- 测试
至此,SpringBoot security安全认证登录的实现就完成了。可以在浏览器中输入“http://localhost:8080/login”进行测试。
如果已经创建了一个名为“user”的角色,并且分配了“ADMIN”角色,并且一个用户名为“admin”、密码为“password”的用户已经被创建,那么在登陆后可以通过请求“/”或“/home”来访问所有网页,但其他网站或者URL就必须经过认证才可以访问。
示例
下面是两个关于SpringBoot security的实例:
示例1:项目初始化
$ mkdir springboot-security-demo
$ cd springboot-security-demo/
$ spring init --dependencies=web,security --package-name=com.example.springbootsecuritydemo --groupId=com.example springboot-security-demo
这将初始化一个项目,并在pom.xml添加以下部分:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
示例2:添加认证接口
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/loginForm", "/registerForm", "/register", "/css/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginForm")
.defaultSuccessUrl("/")
.failureUrl("/loginForm?error=true")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/loginForm?logout=true")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll();
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/js/**");
}
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService(userService);
}
}
以上是SpringBoot security安全认证登录的方法总结,实际开发中可以根据实际需求做适当调整。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot security安全认证登录的实现方法 - Python技术站