1.本项目的结构大概就是这个样子的:
2.首先创建一个spring boot的项目, 项目的version是2.1.3的在配置文件中添加security以及web的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 安全框架 Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.因为本项目没有连接数据库,所以dao、service、serviceimpl、就可以省略掉,直接在写controller中去写界面映射就可以。(注:login.html是登录界面,login-erroe.html是错误界面,main.html是登录成功的界面。)
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
@Controller
public class userController {
@RequestMapping("login")
public String login(){
return "login";
}
@RequestMapping("main")
public String main(){
return "main";
}
@RequestMapping("login-error")
public String loginerror(){
return "login-erroe";
}
}
4,webSecurityConfig 配置文件:需要在内存中创建一个用户并且继承WebSecurityConfigurerAdapter:
package com.example.demo.config;
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 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 安全控制中心
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
//重写该方法来设置一些web安全的细节
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() //通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。
.antMatchers("/", "/home").permitAll() // /和/home不需要任何认证就可以访问。
.anyRequest().authenticated() //其他的路径都必须通过身份验证
.and()
.formLogin() //当需要用户登录时候
.loginPage("/login").loginProcessingUrl("/login/form").successForwardUrl("/main").failureUrl("/login-error") //转到的登录页面
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf().disable();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//inMemoryAuthentication 从内存中获取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
}
}
这样登录的用户名就是user,密码就是123456.
5,下面是login.html页面,只写了一个from表单的提交:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>权限界面登录</title>
</head>
<body>
<p>请登录</p>
<form method="post" action="/login/form">
账号 <input type="text" name="username" placeholder="账号名"/><br />
密码 <input type="text" name="password" placeholder="密码"/><br />
<input type="submit" />
</form>
</body>
</html>
6,启动spring boot项目就可以看到Spring Security已经开始起作用了,可以自己去尝试。