1、概念
安全框架:
shiro、security
主要功能:
- 认证(Authentication):建立用户
- 授权(Authorization):用户可以访问的资源权限
2、使用
(1)依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
(2)配置:
- 写一个配置类
package com.example.sbgj.Config;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
- 定制请求的授权规则,开启登录功能
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//定制请求的授权规则
httpSecurity.authorizeHttpRequests()
.antMatchers("/").permitAll() //所有人都可以访问
.antMatchers("/路径1/**").hasRole("角色1")
.antMatchers("/路径2/**").hasRole("角色2");
//开启登录功能
httpSecurity.formLogin();
//如果没有登录,自动生成登录页面登录
}
- 定义登录认证规则:实际需要从数据库中取,此处模拟
//定义登录认证规则:实际需要从数据库中取,此处模拟
@Override
protected void configure(AuthenticationManagerBuilder managerBuilder) throws Exception {
managerBuilder.inMemoryAuthentication()
.withUser("yan1").password("123456").roles("roles1","roles2")
.and()
.withUser("yan2").password("123456").roles("roles1");
}
- 详细总结
package com.example.sbgj.Config;
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 SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//1-定制请求的授权规则
httpSecurity.authorizeHttpRequests()
.antMatchers("/").permitAll() //所有人都可以访问
.antMatchers("/路径1/**").hasRole("角色1")
.antMatchers("/路径2/**").hasRole("角色2");
//2-开启登录功能
httpSecurity.formLogin().loginPage("/login");//指定登录页
//如果没有登录,自动生成登录页面登录
//3-开启注销
//httpSecurity.logout();
//访问/logout,表示用户注销,清空session,
//注销成功,默认返回登录页,通过修改,可以返回到指定页面
httpSecurity.logout().logoutSuccessUrl("/");
//4-显示用户登录名称和角色
//5-只显示用户授权的页面展示
//6-开启记住登录信息功能
httpSecurity.rememberMe();
//登陆成功会保存一个cookie,下次登录如果有这个cookie,则可以免登录
//注销会删除cookie
}
//定义登录认证规则:实际需要从数据库中取,此处模拟
@Override
protected void configure(AuthenticationManagerBuilder managerBuilder) throws Exception {
managerBuilder.inMemoryAuthentication()
.withUser("yan1").password("123456").roles("roles1","roles2")
.and()
.withUser("yan2").password("123456").roles("roles1");
}
}