SpringBoot集成Spring Security(授权与认证)

⒈添加starter依赖

         <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!--添加Thymeleaf Spring Security依赖-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>

⒉使用配置类定义授权与定义规则

 package cn.coreqi.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; //@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { //定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制请求授权规则
http.authorizeRequests()
.antMatchers("/css/**","/js/**","/fonts/**","index").permitAll() //不拦截,直接访问
.antMatchers("/vip1/**").hasRole("VIP1")
.antMatchers("/vip2/**").hasRole("VIP2")
.antMatchers("/vip3/**").hasRole("VIP3");
//开启登陆功能(自动配置)
//如果没有登陆就会来到/login(自动生成)登陆页面
//如果登陆失败就会重定向到/login?error
//默认post形式的/login代表处理登陆
http.formLogin().loginPage("/userLogin").failureUrl("/login-error");
//开启自动配置的注销功能
//访问/logout表示用户注销,清空session
//注销成功会返回/login?logout页面
//logoutSuccessUrl()设置注销成功后跳转的页面地址
http.logout().logoutSuccessUrl("/");
//开启记住我功能
//登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登陆
//点击注销会删除cookie
http.rememberMe();
} //定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//jdbcAuthentication() 在JDBC中查找用户
//inMemoryAuthentication() 在内存中查找用户 auth.inMemoryAuthentication().withUser("fanqi").password("admin").roles("VIP1","VIP2","VIP3")
.and()
.withUser("zhangsan").password("123456").roles("VIP1");
}
}

⒊编写控制器类(略)

⒋编写相关页面

 <!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<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>
</body>
</html>
上一篇:[转]c3p0学习-JdbcUtil工具类


下一篇:基于Kinetic框架实现超酷的风铃悬挂摆动效果