SpringBoot 和安全(Spring Security)
SpringBoot 和安全(Spring Security)
应用程序的两个主要区域是”认证“和“授权” (访问控制) 这是Spring Security 的两个目标
认证 : 是建立一个他声明的主体的过程(一个主题一般是指用户) 设备 或者 是可以在你应用程序里执行动作的其他系统
授权 : 指确定一个主题是否允许你的应用程序执行一个动作 未来抵达需要授权的店 主体的身份已经有认证过程的建立
这个概念不只是在 Spring Security中
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
编写配置类
package com.zzy.serurity;
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;
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()//拦截所有请求
.antMatchers("/book/**").hasRole("book")//表示book下的所有资源 必须要有book用户才能访问
.antMatchers("/author/**").hasRole("author")
.antMatchers("/student/**").hasRole("student");
//开启自动登录功能 如果没有权限就会来到登录页面
/**
* /login 来到这个页面
* 重定向到/login?error表示登录失败
*
*/
http.formLogin();
/**
* 开启自动注销功能
* http.logout();
* 访问/login 表示用户注销 清空session
*/
http.logout().logoutSuccessUrl("/");//成功推出后去到那个页面
//开启记住我功能 Session Cookie 机制 注意点击注销会清除cookie
http.rememberMe().rememberMeParameter("记住我");//可修改默认值
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//定义一个用户认证规则 从哪获取用户
auth.inMemoryAuthentication().withUser("zs").password("333").roles("book","author")
.and()
.withUser("ls").password("111").roles("book","student");
}
}

浙公网安备 33010602011771号