上一节我们了解了spring与springsecurity的配置整合,在大多数使用中,人们都还是用springboot去整合springsecurity。这一节,我们将看一下springboot与springsecurity的整合。
1、环境约束
- idea2018.1
- maven3.6.1
2、操作步骤
- 创建一个springboot项目,假设名称为springsecuritydemo,pom.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.wanho</groupId>
<artifactId>springsecuritydemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsecuritydemo</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
2.1 使用springsecurity的默认界面
springsecurity提供了默认的登录页面,尽管我们根本不会去用。
- 启动,测试,访问 http://localhost:8080/abcd,会跳转到以下页面:
2.2 配置约束路径和固定账号密码
- 在项目/src/resources/templates文件夹下创建文件:
login.html
<!DOCTYPE html>
<html id="ng-app" ng-app="app">
<head>
<meta charset="UTF-8"/>
<title>home</title>
</head>
<body>
<form class="form-signin" action="/form" method="post">
<h2 class="form-signin-heading">用户登录</h2>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" class="form-control" placeholder="请输入用户名"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" class="form-control" placeholder="请输入密码" /></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-lg btn-primary btn-block" >登录</button>
</td>
</tr>
</table>
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
>
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
error.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head>
<title>Hello World!</title>
</head>
<body>
出错了或者没权限
<a href="/login">去登录</a>
</body>
</html>
- 在项目/src/main/java文件夹下创建MvcConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/login").setViewName("login");
}
}
- 在项目/src/main/java文件夹下创建WebSecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/login").permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.csrf().disable()//关闭CSRF
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/form")
.defaultSuccessUrl("/index") //成功登陆后跳转页面
.failureUrl("/loginError").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("ali").password("123456").roles("USER")
.and()
.withUser("xiaoli").password("123456").roles("ADMIN");
}
- 启动,测试
1,访问http://localhost:8080/abcd,跳转到以下页面:
2,输入xiaoli/123456,点击登录,跳转到以下页面:
3,重新登陆,输入xiaoli/123456,点击登录,跳转到以下页面:
2.3 从“数据库”中获取密码
之所以将数据库加密码是因为我们并没有真的去查数据库,而是固定的账号密码。
- 在项目/src/main/java文件夹下创建Role.java
public class Role {
private long id;
private String name;
public Role(long id, String name) {
this.id = id;
this.name = name;
}
public Role() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 在项目/src/main/java文件夹下创建User.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.List;
public class User implements UserDetails {
private Long id;
private String username;
private String password;
private List<Role> roles;
@Override
@JsonIgnore
public boolean isAccountNonExpired() { // 帐户是否过期
return true;
}
@Override
@JsonIgnore
public boolean isAccountNonLocked() { // 帐户是否被冻结
return true;
}
// 帐户密码是否过期,一般有的密码要求性高的系统会使用到,比较每隔一段时间就要求用户重置密码
@Override
@JsonIgnore
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() { // 帐号是否可用
return true;
}
@Override
@JsonIgnore
public List<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
- 在项目/src/main/java文件夹下创建MyUserDetailsService.java
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("admin")) {
//假设返回的用户信息如下,这里本应该去查数据库,但我们的关注点不在存储,所以这里写固定了
User userInfo = new User();
userInfo.setUsername("admin");
userInfo.setPassword("123456");
Role role = new Role(1L, "USER");
List<Role> list = new ArrayList();
list.add(role);
userInfo.setRoles(list);
return userInfo;
}
return null;
}
}
- 在项目/src/main/java文件夹下创建MyAuthenticationProvider.java
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Resource
private UserDetailsService userDetailService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = authentication.getName();// 这个获取表单输入中返回的用户名;
String password = (String) authentication.getCredentials();// 这个是表单中输入的密码;
User userInfo = (User) userDetailService.loadUserByUsername(userName); // 这里调用我们的自己写的获取用户的方法;
if (userInfo == null) {
throw new BadCredentialsException("用户名不存在");
}
if (!userInfo.getPassword().equals(password)) {
throw new BadCredentialsException("密码不正确");
}
Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
- 修改WebSecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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 javax.annotation.Resource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/login").permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.csrf().disable()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/form")
.defaultSuccessUrl("/index")
.failureUrl("/error").permitAll();
}
@Resource
MyAuthenticationProvider provider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(provider);
}
}
- 启动,测试
1,访问http://localhost:8080/abcd,出现以下界面:
2,输入admin/123456,点击登录,出现以下界面:
3,再次访问http://localhost:8080/abcd,出现以下页面:
至此,我们完成了springboot与springsecurity的整合。