在Spring Boot中使用Spring Security的基本步骤如下:
1,添加Spring Security依赖到你的 pom.xml 文件中:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
2,配置WebSecurityConfigurerAdapter来定义安全策略。
如,你可以设置哪些URL是公开的,哪些需要认证等。
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/", "/home").permitAll() // 所有人都可访问.antMatchers("/500","/403","/404").permitAll() // 所有人都可访问.antMatchers("/sell/*").hasRole("sell") // 仅有sell角色可访问的URL.antMatchers("/admin/**").hasRole("admin") // 仅有admin角色访问的URL.anyRequest().authenticated() // 任何其它请求,都需要身份认证.and()//2、登录配置表单认证方式.formLogin().loginPage("/login") // 自定义的登录页面.usernameParameter("username") // 自定义登录页面的入参用户名.usernameParameter("password") // 自定义登录页面的入参密码.loginProcessingUrl("/doLogin") //上面登录表单提交url,不需要再控制层写/doLogin.permitAll().defaultSuccessUrl("/index") //登录成功后默认的跳转页面路径.failureUrl("/login?error=true").successHandler(loginSuccessHandler) //使用自定义的成功结果处理器.failureHandler(loginFailureHandler) //使用自定义失败的结果处理器.and() //3、退出.logout().logOutPage("logout") // 默认对应 logout.html.permitAll().and().rememberMe() // 登录之后记住我,即将cookie发送给客户端保存.rememberMeParameter("myPage") //自定义页面参数.and()//4、session管理.sessionManagement().invalidSessionUrl("/login") //失效后跳转到登陆页面//单用户登录,如果有一个登录了,同一个用户在其他地方登录将前一个剔除下线//.maximumSessions(1).expiredSessionStrategy(expiredSessionStrategy())//单用户登录,如果有一个登录了,同一个用户在其他地方不能登录//.maximumSessions(1).maxSessionsPreventsLogin(true) ;.and()//5、禁用跨站csrf攻击防御.csrf().disable();}@Overridepublic void configure(HttpSecurity http) throws Exception {superconfigure(http);//配置静态文件(css,js,git/png等图片)不需要认证http.ignoring().antMatchers("/static/**");// ...更多设置...}/** 加密对象,对用户密码进行加密用*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}}
3,创建一个Controller来处理登录和注销请求。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class SecurityController {@GetMapping("/login")public String login() {return "login";}@GetMapping("/logout")public String logout() {return "logout";}/**方式一,获取登录用户信息, 通过 SecurityContext 对象获取SecurityContext 对象,用该对象获取登录用户信息 */@GetMapping("/userInfo")@ResponseBodypublic Map<String, String> getUserInfo() {SecurityContext context = SecurityContextHolder.getContext();Authentication authentication = context.getAuthentication();// org.springframework.security.core.userdetails.UserUser user = (User) authentication.getPrincipal();Map<String, String> map = new HashMap<>();map.put("username",user.getUsername());map.put("authorities",user.getAuthorities());return map;}/**方式二,获取登录用户信息, 通过 @SessionAttribute 从Session中获取 */@GetMapping("/userInfo2")@ResponseBodypublic Map<String, String> getUserInfo2(@SessionAttribute("SPRING_SECURITY_CONTEXT") SecurityContext context) { Authentication authentication = context.getAuthentication();// org.springframework.security.core.userdetails.UserUser user = (User) authentication.getPrincipal();Map<String, String> map = new HashMap<>();map.put("username",user.getUsername());map.put("authorities",user.getAuthorities());return map;}}
4,创建对应的登录页面和注销页面的HTML模板。
登录页面 (login.html):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org">
<head><title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form th:action="@{/login}" method="post"><div><label> Username: <input type="text" name="username"/> </label></div><div><label> Password: <input type="password" name="password"/> </label></div><div><input type="submit" value="Login"/></div>
</form>
</body>
</html>
注销或退出页面 (logout.html):
<!DOCTYPE html>
<html>
<head><title>登出页面</title>
</head>
<body>
<h2>你已经退出系统.</h2>
</body>
</html>
5,创建一个启动类SpringBootJpaApplication:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBootDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringBootDemoApplication.class, args);}
}
6,确保你的应用程序使用了Spring Security的自动配置。如果你需要自定义更多的安全特性,
你可以创建一个 @Configuration 类来扩展或覆盖默认配置。
以上步骤提供了一个基本的安全配置,允许你开始在Spring Boot应用程序中使用Spring Security。
根据你的具体需求,你可能需要进一步定制安全配置。