SpringBoot中如何使用Spring Security安全框架

在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 {
 
    @Override
    protected 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();
    }
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
	   superconfigure(http);
	   
	   //配置静态文件(css,js,git/png等图片)不需要认证
       http.ignoring().antMatchers("/static/**");
	   
	   // ...更多设置...
	}
	
	/** 加密对象,对用户密码进行加密用*/
	@Bean
    public 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")
	@ResponseBody
	public Map<String, String> getUserInfo() {
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication authentication = context.getAuthentication();
		// org.springframework.security.core.userdetails.User
		User 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")
	@ResponseBody
	public Map<String, String> getUserInfo2(
		@SessionAttribute("SPRING_SECURITY_CONTEXT") SecurityContext context
		) {		
		Authentication authentication = context.getAuthentication();
		// org.springframework.security.core.userdetails.User
		User 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。
根据你的具体需求,你可能需要进一步定制安全配置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring SecuritySpring 生态系统用于身份验证和授权的框架Spring BootSpring Security 提供了自动配置和便捷的集成方式。 以下是 Spring Boot 如何使用 Spring Security: 1. 在 Maven 或 Gradle 添加 Spring Security 的依赖。 2. 创建一个继承自 WebSecurityConfigurerAdapter 的类,并在其重写 configure() 方法来进行安全配置。 3. 在 configure() 方法设置需要进行保护的 URL 和权限,以及用户认证的方式。可以使用内存、数据库或 LDAP 进行用户认证。 4. 如果需要自定义登录页面,可以创建一个继承自 WebSecurityConfigurerAdapter 的类,并在其添加一个配置类,重写 configure(HttpSecurity http) 方法来配置登录页面的 URL 和表单参数。 5. 如果需要在认证成功或失败后进行一些操作,可以使用 AuthenticationSuccessHandler 或 AuthenticationFailureHandler 接口。 6. 如果需要在用户注销后进行一些操作,可以使用 LogoutHandler 接口。 7. 如果需要启用 CSRF 防护,可以在 configure(HttpSecurity http) 方法添加 .csrf() 方法。 8. 如果需要启用 remember-me 功能,可以在 configure(HttpSecurity http) 方法添加 .rememberMe() 方法。 9. 如果需要启用 HTTP Basic 认证,可以在 configure(HttpSecurity http) 方法添加 .httpBasic() 方法。 10. 最后,在 Spring Boot 应用程序的启动类上添加 @EnableWebSecurity 注解即可启用 Spring Security。 以上是 Spring Boot 使用 Spring Security 的简单步骤,具体实现可以参考 Spring Security 官方文档和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值