SpringBoot整合Spring-Security

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangminemail/article/details/82946243

1、添加依赖

// 添加spring security依赖
	compile('org.springframework.boot:spring-boot-starter-security')
	// 添加Thymeleaf spring security依赖
	compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')

2、集成接口WebSecurityConfigurerAdapter

import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * 安全配之类
 * @author Administrator
 *
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	/**
	 * 自定义配置
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll() // 都可以访问
			.antMatchers("/users/**").hasRole("ADMIN") // 需要相应的角色才能访问
			.and()
			.formLogin() // 基于表单Form登录验证
			.loginPage("/login").failureUrl("/login-error");//自定义登录界面
	}
	
	/**
	 * 认证管理信息
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
		auth.inMemoryAuthentication() // 认证信息存储于内存中
			.withUser("waylau").password("123456").roles("ADMIN");
	}
}

3、页面运用

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
<!-- Page Content -->
<div class="container blog-content-container">

    <div sec:authorize="isAuthenticated()">
    	<p>已有用户登录</p>
    	<p>登录的用户为:<span sec:authentication="name"></span> </p>
    	<p>用户角色为:<span sec:authentication="principal.authorities"></span> </p>
    </div>
	<div sec:authorize="isAnonymous()">
		<p>未有用户登录</p>
	</div>

</div>
<!-- /.container -->


<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zhangminemail/article/details/82946243