spring security oauth2
作用:登录访问权限的管理
1.创建springboot 项目选中这两个
创建成功后创建controller 编写一个Controller 访问该地址
出现登录页面
用户名默认为user 密码就是启动时的字符串
使用Web安全配置适配器
编写一个配置类 选中一个接口 按住ctrl+H 就能看到该接口的实现类
public class MyWebSercurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//密码加密器
PasswordEncoder pe=passwordEncoder();
//创建用户
auth.inMemoryAuthentication()
.withUser("xf") //设置用户名
.password(pe.encode("root")) //设置用户密码
.roles(); //为用户添加权限角色
auth.inMemoryAuthentication()
.withUser("lisi")
.password(pe.encode("root"))
.roles("admin");
auth.inMemoryAuthentication()
.withUser("zhangsan")
.password("root")
.roles("admin","root");
}
@Bean //自动注入密码加密器
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
编写controller 类
@Controller
@RequestMapping("/user")
public class SecurityController {
@RequestMapping("/login")
@ResponseBody
public String first(){
return "访问成功";
}
@ResponseBody
@RequestMapping("/login1")
@PreAuthorize(value = "hasAnyRole('admin')") //允许使用用户的角色 访问
public String first1(){
return " admin 访问成功";
}
@ResponseBody
@RequestMapping("/login2")
@PreAuthorize(value = "hasAnyRole('admin,root')")
public String first2(){
return "admin,root 访问成功";
}
}
在启动类添加注解
@SpringBootApplication
@EnableWebSecurity //
@EnableGlobalMethodSecurity(prePostEnabled = true) // controller层@PreAuthorize 注解生效
public class Security4002 {
public static void main(String[] args) {
SpringApplication.run(Security4002.class, args);
}
}
@EnableWebSecurity的作用
1: 加载了WebSecurityConfiguration配置类, 配置安全认证策略。
2: 加载了AuthenticationConfiguration, 配置了认证信息。
@EnableGlobalMethodSecurity 详解
@EnableGlobalMethodSecurity(securedEnabled=true)
开启@Secured 注解过滤权限
例如:@Secured({“ROLE_EMP”})、@Secured({“ROLE_EMP”, “ROLE_ROOT”})、@Secured({“ROLE_ROOT”})
@EnableGlobalMethodSecurity(jsr250Enabled=true)
开启@RolesAllowed 注解过滤权限
@EnableGlobalMethodSecurity(prePostEnabled=true)
使得表达式时间方法级别的安全性4个注解可用
@PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
@PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
@PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
@PreFilter 允许方法调用,但必须在进入方法之前过滤输入值