1、简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
2、基本功能
-
认证
-
权限
3、简单demo
-
创建简单springboot项目,选择以下依赖
-
直接启动项目,显示以下界面,是security默认拦截界面
生成密码如下所示:
-
简单实现登录
代码:
login.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="/login" method="post">
用户名:<input type="text" name="username" value=""><br>
密码:<input type="password" name="password" value=""><br>
<input type="submit" value="登录">
</form>
</body>
</html>
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<titl>首页</titl></title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
-
controller层LoginController
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(){
return "redirect:main.html";
}
}
-
浏览器访问
http://localhost:8080/login.html
4、自定义登录逻辑
-
添加error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录失败!!!!</h1>
<a href="/login.html">跳转</a>
</body>
</html>
-
添加SecurityConfig.java核心配置文件
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//表单登录
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
//必须是post请求,成功后跳转
.successForwardUrl("/toMain")
//必须是post请求,失败后跳转
.failureForwardUrl("/toError");
//授权
http.authorizeRequests()
//放行
.antMatchers("/login.html").permitAll()
.antMatchers("/error.html").permitAll()
//所有请求都必须通过认证才能访问
.anyRequest().authenticated();
http.csrf().disable();
}
@Bean
public PasswordEncoder getPw(){
return new BCryptPasswordEncoder();
}
}
-
security用户判断实现类
注意User类不是自定义的,而是security包中的
@Service
public class UserDatailServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//1、根据用户名查询数据
if (!"admin".equals(username)){
throw new UsernameNotFoundException("用户名不存在");
}
//2、比较密码
String encode = passwordEncoder.encode("123");
return new User(username,encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
-
LoginController.java添加代码
@RequestMapping("/toMain")
public String toMain(){
return "redirect:main.html";
}
@RequestMapping("/toError")
public String toError(){
return "redirect:error.html";
}
-
启动测试
END
敬请期待SpringSecurity(二)。。。