SpringBoot集成Spring Security做登录验证

1.概述

这篇文章介绍如何在SpringBoot中配置Spring Security,用作安全登录。

2.maven依赖

在pom.xml中添加Spring Security相关依赖:
pom.xml.

		<!-- spring security starter -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

3.配置Spring Security

你需要继承WebSecurityConfigurerAdapter

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	/**
	 * 配置用户认证
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//在内存中创建相关用户,配置相应的角色
		auth.inMemoryAuthentication()
			.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER")
			.and()
			.withUser("user2").password(passwordEncoder().encode("user2Pass")).roles("USER")
			.and()
			.withUser("admin").password(passwordEncoder().encode("adminPass")).roles("ADMIN");
	}

	/**
	 * 配置http相关安全特性
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.authorizeRequests()
				.antMatchers("/admin/**").hasRole("ADMIN") // /admin开头的url需要ADMIN角色才能访问
				.antMatchers("/anonymous*").anonymous() // 未登录用户可访问
				.antMatchers("/login*").permitAll() // 所有人可访问
				.anyRequest().authenticated() // 其他url都需要登陆才能访问
			.and() // 前面antMatchers等相当于authorizeRequests的子标签,and将标签闭合
			.formLogin()
				.loginPage("/login.html") // 指定登陆页面url
				.loginProcessingUrl("/perform_login") // 处理登陆的url
				.defaultSuccessUrl("/homepage.html", true) // 登陆成功重定向到该页面
				.failureHandler(authenticationFailureHandler())
			.and()
			.logout()
				.logoutUrl("/perform_logout") //指定登出请求的url
				.deleteCookies("JSESSIONID")
				.logoutSuccessHandler(logoutSuccessHandler())
			.and()
			.exceptionHandling()
				.accessDeniedHandler(accessDeniedHandler());
	}

	/**
	 * 密码hash算法
	 * 
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	/**
	 * 认证失败后的处理器
	 * 
	 * @return
	 */
	@Bean
	public AuthenticationFailureHandler authenticationFailureHandler() {
		return new CustomAuthenticationFailHandler();
	}

	/**
	 * 退出登陆处理器
	 * @return
	 */
	@Bean
	public LogoutSuccessHandler logoutSuccessHandler() {
		return new CustomLogoutHandler();
	}

	/**
	 * 权限验证失败处理器
	 * @return
	 */
	@Bean
	public AccessDeniedHandler accessDeniedHandler() {
		return new CustomAccessDeniedHandler();
	}

}

注意:

  • 默认情况下,Spring Security自动生成登陆页面,默认url为 /login
  • 通过loginPage方法,我们指向了自定义的登录页面
  • 指定了 /peform_login 处理登录请求,该url由Spring Security处理,不需要自己编写

类似的,Spring Security提供了很多默认配置,而我们通过WebSecurityConfigurerAdapter来覆盖默认的配置。

5. Thymeleaf集成Spring Security

5.1 maven依赖

要在模板文件中,使用SpringSecurity相关特性,需要添加如下依赖:

		<!-- themyleaf集成spring security-->
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity5</artifactId>
		</dependency>

5.2 thymeleaf验证Spring Security权限

通过执行 hasRole方法,themyleaf通过Spring Security验证了用户的角色信息:

	<!-- 角色为USER,展示下面的信息 -->
	<!-- themyleaf spring security integration -->
	<div th:if="${#authorization.expression('hasRole(''ROLE_USER'')')}">
         This text is only visible to a user
        <br/> <br/>
        <a href="/admin/adminpage.html">Restricted Admin Page</a>
        <br/> <br/>
    </div>
    
    <!-- 角色为ADMIN,展示下面的信息 -->
    <!-- themyleaf spring security integration -->
	<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
         This text is only visible to an admin
        <br/>
        <a href="/admin/adminpage.html">Admin Page</a>
        <br/>
    </div>

6.总结

本文介绍了如何在SpringBoot下配置Spring Security,并介绍了如何在thymeleaf中集成Spring Security。
完整项目在github上: https://github.com/superOTAKU/springSecurity
git clone 导入后即可运行。

猜你喜欢

转载自blog.csdn.net/qq_21508059/article/details/88776706