Spring Security

来源:互联网 发布:淘宝上卖千岛片真的么 编辑:程序博客网 时间:2024/05/29 03:42

Spring Security

Spring Security是基于spring的应用程序提供声明式安全保护的安全性框架,它提供了完整的安全性解决方案,能够在web请求级别和方法调用级别处理身份证验证和授权,启动时,就加载全部权限.

引入jar包

<dependency>                                                                         <groupId>org.springframework.boot</groupId>                                 <artifactId>spring-boot-starter-security</artifactId></dependency>

代码

//内存认证@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {// 用户名和密码auth.inMemoryAuthentication().withUser("user").password("1234").roles("users").and().withUser("root").password("1234").roles("root").and().withUser("teacher").password("1234").roles("teacher");    System.out.println("yyyyyyyyyyyy");}public void configure(HttpSecurity http) throws Exception {// 登录页 http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();// 自定义登录页http.csrf().disable();http.authorizeRequests().antMatchers("/webjars/**", "/signup", "/about").permitAll().antMatchers("/admin/**").hasRole("UADMINSER").antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')").anyRequest()           .authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().and().httpBasic();System.out.println("xxxxxxxxxxxxxx");}

Spring Security 支持的所有SpEL表达式 

安全表达式 计算结果 authentication 用户认证对象 denyAll 结果始终为false hasAnyRole(list of roles) 如果用户被授权指定的任意权限,结果为true hasRole(role) 如果用户被授予了指定的权限,结果 为true hasIpAddress(IP Adress) 用户地址 isAnonymous() 是否为匿名用户 isAuthenticated() 不是匿名用户 isFullyAuthenticated 不是匿名也不是remember-me认证 isRemberMe() remember-me认证 permitAll 始终true principal 用户主要信息对象

权限控制方式

安全表达式 计算结果 access(String) SpringEL表达式结果为true时可访问 anonymous() 匿名可访问 denyAll() 不可访问 fullyAuthenticated() 用户完全认证可访问 hasAnyAuthority(String…) 参数中任意权限的用户可访问 hasAnyRole(String…) 参数中任意角色的用户可访问 hasAuthority(String) 某一权限的用户可访问 hasRole(String) 某一角色的用户可访问 permitAll() 所有用户可访问 rememberMe() 允许通过remember me 登录的用户访问 authenticated 用户登录可访问 haslpAddress(String) 用户来自参数的IP可访问
原创粉丝点击