Security简介
Spring 是非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
核心功能:
- 用户认证(Authentication):系统判断用户是否能登录
- 用户授权(Authorization):系统判断用户是否有权限去做某些事情
特点:
- Spring 技术栈的组成部分,与Spring 无缝整合。
- 全面的权限控制,能提供完整可扩展的认证和授权支持保护
- 专门为 Web开发而设计。
- 重量级,需要引入各种家族组件与依赖
项目结构
代码部分
1、pom文件
<!--Springboot启动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Spring Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!--mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!--Spring Security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2、yml配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/websocket
driver-class-name: com.mysql.jdbc.Driver
thymeleaf:
cache: false
#prefix: classpath:/templates/
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
typeAliasesPackage: com.iss.security.*.entity
# mapperLocations: classpath:mapper/*.xml
3、security配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author 流星
* security配置类
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
/**
* 自定义无访问权限跳转的页面
*/
http.exceptionHandling()
.accessDeniedPage("/403.html");
/**
* 自定义登陆页面
*/
http.formLogin()
//登陆页面设置
.loginPage("/index.html")
//登陆访问路径
.loginProcessingUrl("/user/login")
//登陆成功后跳转路径
.defaultSuccessUrl("/success.html").permitAll()
.and()
.authorizeRequests()
//设置不需要认证的访问路径,可以直接访问
.antMatchers("/", "/user/login").permitAll()
//当前用户只有具有addUser权限时才能访问该路径
// .antMatchers("/test/addUser").hasAuthority("addUser")
// .antMatchers("/test/findAll").hasAnyAuthority("addUser,findAll")
// .antMatchers("/test/hello").hasRole("admin")
// .antMatchers("/test/hello").hasAnyRole("admin")
.anyRequest().authenticated()
.and()
//关闭csrf的保护
.csrf().disable();
http.logout()
//退出的地址
.logoutUrl("/logout")
.logoutSuccessUrl("/index.html").permitAll();
}
@Bean
PasswordEncoder password() {
return new BCryptPasswordEncoder();
}
}
4、MyUserDetailsService
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iss.security.login.entity.SysUser;
import com.iss.security.login.mapper.SysUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 进行认证操作
*
* @author lx
* @since 2022-06-05 13:01:06
*/
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Resource
private SysUserMapper sysUserMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用usersMapper方法,根据用户名查询数据库
QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
wrapper.eq("user_name",username);
SysUser users = sysUserMapper.selectOne(wrapper);
if(users==null){
//数据库没有数据,认证失败
throw new UsernameNotFoundException("用户名不存在!");
}
//手动设置权限,也可以通过数据库查询获取
List<GrantedAuthority> auths = AuthorityUtils
.commaSeparatedStringToAuthorityList("addUser,findAll,ROLE_admin,ROLE_user");
return new User(users.getUserName(),
new BCryptPasswordEncoder().encode(users.getPassword()),auths);
}
}
5、entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUser implements Serializable {
private Integer id;
private String userName;
private String password;
private String qqMail;
private String role;
}
6、mybatis-plus
7、html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="hidden" name="_csrf.parameterName" th:value="${_csrf.token}" th:if="${_csrf}!=null"/>
<form action="/user/login" method="post">
<!--注意:页面提交方式必须为 post 请求,用户名,密码必须为username,password
可以通过 usernameParameter()和 passwordParameter()方法修改默认配置-->
用户名:<input type="text" name="username">
<br/>
密码:<input type="password" name="password">
<br/>
<input type="submit" value="login">
</form>
</body>
</html>
测试结果
扩展资料
权限控制: