Spring security @preauthorize

玩转Spring Boot 使用Spring security


      Spring Boot与Spring Security在一起开发非常简单,充分体现了自动装配的强大,Spring Security是Spring Boot官方推荐使用的安全框架。配置简单,功能强大。接下来将说说Spring Boot使用Spring security进行安全控制。

1.Spring Boot 内置属性参数

      Spring Boot 提供的内置配置参数以security为前缀,具体属性如下:
# SECURITY (SecurityProperties 类中)
security.basic.authorize-mode=role # 应用授权模式,ROLE=成员必须是安全的角色,AUTHENTICATED=经过身份验证的用户,NONE=没有设置安全授权
security.basic.enabled=true # 启用基本身份认证
security.basic.path=/** # 拦截策略,以逗号分隔
security.basic.realm=Spring # HTTP基本realm
security.enable-csrf=false # 启用csrf支持
security.filter-order=0 # 过滤器执行顺序
security.filter-dispatcher-types=ASYNC, FORWARD, INCLUDE, REQUEST # security 过滤器链dispatcher类型
security.headers.cache=true # 启用缓存控制 HTTP headers.
security.headers.content-type=true # 启用 "X-Content-Type-Options" header.
security.headers.frame=true # 启用 "X-Frame-Options" header.
security.headers.hsts= # HTTP Strict Transport Security (HSTS) mode (none, domain, all).
security.headers.xss=true # 启用跨域脚本 (XSS) 保护.
security.ignored= # 安全策略,以逗号分隔
security.require-ssl=false # 启用所有请求SSL
security.sessions=stateless # Session 创建策略(always, never, if_required, stateless).
security.user.name=user # 默认用户名
security.user.password= # 默认用户名密码
security.user.role=USER # 默认用户角色

# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties 类中)
security.oauth2.client.client-id= # OAuth2 client id.
security.oauth2.client.client-secret= # OAuth2 client secret. A random secret is generated by default

# SECURITY OAUTH2 RESOURCES (ResourceServerProperties 类中)
security.oauth2.resource.id= # Identifier of the resource.
security.oauth2.resource.jwt.key-uri= # The URI of the JWT token. Can be set if the value is not available and the key is public.
security.oauth2.resource.jwt.key-value= # The verification key of the JWT token. Can either be a symmetric secret or PEM-encoded RSA public key.
security.oauth2.resource.prefer-token-info=true # Use the token info, can be set to false to use the user info.
security.oauth2.resource.service-id=resource #
security.oauth2.resource.token-info-uri= # URI of the token decoding endpoint.
security.oauth2.resource.token-type= # The token type to send when using the userInfoUri.
security.oauth2.resource.user-info-uri= # URI of the user endpoint.

# SECURITY OAUTH2 SSO (OAuth2SsoProperties 类中)
security.oauth2.sso.filter-order= # Filter order to apply if not providing an explicit WebSecurityConfigurerAdapter
security.oauth2.sso.login-path=/login # Path to the login page, i.e. the one that triggers the redirect to the OAuth2 Authorization Server

以上是官方给出的配置属性以及默认值列表。

2.security Starter Poms

[html]  view plain  copy
  1. <dependency>  
  2.             <groupId>org.springframework.boot</groupId>  
  3.             <artifactId>spring-boot-starter-security</artifactId>  
  4.         </dependency>  

3.security hello world

3.1创建工程
      创建工程springboot-security并加入security Starter Poms,完整代码如下:
[html]  view plain  copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.chengli</groupId>  
  5.     <artifactId>springboot-security</artifactId>  
  6.     <version>0.0.1-SNAPSHOT</version>  
  7.     <packaging>jar</packaging>  
  8.     <name>springboot-security</name>  
  9.     <url>http://maven.apache.org</url>  
  10.     <parent>  
  11.         <groupId>org.springframework.boot</groupId>  
  12.         <artifactId>spring-boot-starter-parent</artifactId>  
  13.         <version>1.4.3.RELEASE</version>  
  14.     </parent>  
  15.     <properties>  
  16.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  17.         <java.version>1.8</java.version>  
  18.     </properties>  
  19.     <dependencies>  
  20.         <dependency>  
  21.             <groupId>org.springframework.boot</groupId>  
  22.             <artifactId>spring-boot-starter</artifactId>  
  23.         </dependency>  
  24.         <dependency>  
  25.             <groupId>org.springframework.boot</groupId>  
  26.             <artifactId>spring-boot-starter-web</artifactId>  
  27.         </dependency>  
  28.         <dependency>  
  29.             <groupId>org.springframework.boot</groupId>  
  30.             <artifactId>spring-boot-starter-security</artifactId>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.springframework.boot</groupId>  
  34.             <artifactId>spring-boot-devtools</artifactId>  
  35.             <optional>true</optional>  
  36.         </dependency>  
  37.     </dependencies>  
  38.     <build>  
  39.         <plugins>  
  40.             <plugin>  
  41.                 <groupId>org.springframework.boot</groupId>  
  42.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  43.             </plugin>  
  44.         </plugins>  
  45.     </build>  
  46. </project>  

3.2创建入口启动类
[java]  view plain  copy
  1. package com.chengli.springboot;  
  2.   
  3. import org.springframework.boot.SpringApplication;  
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  5. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. @SpringBootApplication  
  11. @EnableWebSecurity //启用web安全  
  12. public class MainConfig {  
  13.     public static void main(String[] args) {  
  14.         SpringApplication.run(MainConfig.class, args);  
  15.     }  
  16.   
  17.     @RequestMapping("/security")  
  18.     public String security() {  
  19.         return "hello world security";  
  20.     }  
  21. }  

3.3创建application.properties
      在application.properties中设置默认用户名以及默认密码
[html]  view plain  copy
  1. security.user.name=chengli  
  2. security.user.password=123456  

3.4启动
      到这里我们直接运行MainConfig试试吧,在浏览器上输入:http://localhost:8080/security,Spring security会为我们提供一个默认的登录页面,界面如下:


输入用户名密码登录进去,页面上会显示hello world security。

4.自定义security

      实际开发中,不可能都用security提供的默认配置,我们需要自定义一些配置,比如拦截的请求路径,以及从数据库中获取用户等等,那么接下来说说一些常用的配置。以下代码建立在以上工程中。
4.1新建security配置类:SecurityConfig
      新建SecurityConfig类并继承WebSecurityConfigurerAdapter,WebSecurityConfigurerAdapter是security提供用于更改默认配置,实现configure方法,代码如下:
[java]  view plain  copy
  1. package com.chengli.springboot.security;  
  2.   
  3. import org.springframework.context.annotation.Configuration;  
  4. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;  
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
  8.   
  9. @Configuration  
  10. @EnableWebSecurity  
  11. public class SecurityConfig extends WebSecurityConfigurerAdapter {  
  12.       
  13.     /**定义认证用户信息获取来源,密码校验规则等*/  
  14.     @Override  
  15.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
  16.         //inMemoryAuthentication 从内存中获取  
  17.         auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER");  
  18.           
  19.         //jdbcAuthentication从数据库中获取,但是默认是以security提供的表结构  
  20.         //usersByUsernameQuery 指定查询用户SQL  
  21.         //authoritiesByUsernameQuery 指定查询权限SQL  
  22.         //auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(query).authoritiesByUsernameQuery(query);  
  23.           
  24.         //注入userDetailsService,需要实现userDetailsService接口  
  25.         //auth.userDetailsService(userDetailsService);  
  26.     }  
  27.       
  28.     /**定义安全策略*/  
  29.     @Override  
  30.     protected void configure(HttpSecurity http) throws Exception {  
  31.         http.authorizeRequests()//配置安全策略  
  32.             .antMatchers("/","/hello").permitAll()//定义/请求不需要验证  
  33.             .anyRequest().authenticated()//其余的所有请求都需要验证  
  34.             .and()  
  35.         .logout()  
  36.             .permitAll()//定义logout不需要验证  
  37.             .and()  
  38.         .formLogin();//使用form表单登录  
  39.     }  
  40.       
  41. }  

4.2在入口启动类MainConfig加入以下方法
      这里为了方便演示就在加入一个方法
[java]  view plain  copy
  1. @RequestMapping("/hello")  
  2.     public String hello() {  
  3.         return "不验证哦";  
  4.     }  
4.4启动
      启动后,在浏览器上输入:http://localhost:8080/hello,我们看到是不需要验证直接在页面上输出:不验证哦。那在输入:http://localhost:8080/security,我们看到是需要进行验证的,那么输入用户名:chengli,密码:123456,我们看到页面输出:hello world security。这里为了方便演示用户信息是放在内存中,实际项目中使用数据库验证可以使用jdbc也可以实现userDetailsService类。

4.5开启方法权限校验
      在SecurityConfig类加上注解:@EnableGlobalMethodSecurity,该注解可以开启prePostEnabled,securedEnabled,jsr250Enabled的支持,这里演示使用@EnableGlobalMethodSecurity(prePostEnabled = true),开启对prePostEnabled 支持。在方法上加入@PreAuthorize注解,@PreAuthorize注解支持使用SpEL表达式。这里我们在MainConfig类中加入以下代码:
[java]  view plain  copy
  1. @PreAuthorize("hasRole('ROLE_ADMIN')")  
  2.     @RequestMapping("/authorize")  
  3.     public String authorize() {  
  4.         return "有权限访问";  
  5.     }  
在增加一个用户admin,修改以下代码,如下:
[java]  view plain  copy
  1. 修改前:  
  2. auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER")  
  3. 修改后:  
  4. auth.inMemoryAuthentication().withUser("chengli").password("123456").roles("USER")  
  5.         .and().withUser("admin").password("123456").roles("ADMIN");  

这里我们在启动使用chengli登录后访问/authorize会返回403错误,使用admin登录访问页面输出有权限访问。

既然登录了那就有退出,默认的退出地址在LogoutConfigurer类中,当然也是可以自定义的,这里就不说了,在定义安全策略方法中调用即可。我们也可以在浏览器中输入logout退出,这里会出现错误,因为security默认开启了csrf,这里我为了方便就禁用了csrf。禁用代码如下:
[java]  view plain  copy
  1. //禁用csrf  
  2.         http.csrf().disable();  

这里对于spring security的内容就不介绍了,具体的看官方文档。
如果想学习Spring security 又对英文的文档望而生怯的话,那么给大家推荐一个系列博文:http://www.iteye.com/blogs/subjects/spring_security,作者写的还比较清楚就是版本相对于现在来说有点低,如果想学习新的特性那么还是看官方的文档吧。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
序言 I. 入门 1. 介绍 1.1. Spring Security是什么? 1.2. 历史 1.3. 发行版本号 1.4. 获得Spring Security 1.4.1. 项目模块 1.4.1.1. Core - spring-security-core.jar 1.4.1.2. Web - spring-security-web.jar 1.4.1.3. Config - spring-security-config.jar 1.4.1.4. LDAP - spring-security-ldap.jar 1.4.1.5. ACL - spring-security-acl.jar 1.4.1.6. CAS - spring-security-cas-client.jar 1.4.1.7. OpenID - spring-security-openid.jar 1.4.2. 获得源代码 2. Security命名空间配置 2.1. 介绍 2.1.1. 命名空间的设计 2.2. 开始使用安全命名空间配置 2.2.1. 配置web.xml 2.2.2. 最小 <http>配置 2.2.2.1. auto-config包含了什么? 2.2.2.2. 表单和基本登录选项 2.2.3. 使用其他认证提供器 2.2.3.1. 添加一个密码编码器 2.3. 高级web特性 2.3.1. Remember-Me认证 2.3.2. 添加HTTP/HTTPS信道安全 2.3.3. 会话管理 2.3.3.1. 检测超时 2.3.3.2. 同步会话控制 2.3.3.3. 防止Session固定攻击 2.3.4. 对OpenID的支持 2.3.4.1. 属性交换 2.3.5. 添加你自己的filter 2.3.5.1. 设置自定义 AuthenticationEntryPoint 2.4. 保护方法 2.4.1. <global-method-security>元素 2.4.1.1. 使用protect-pointcut添加安全切点 2.5. 默认的AccessDecisionManager 2.5.1. 自定义AccessDecisionManager 2.6. 验证管理器和命名空间 3. 示例程序 3.1. Tutorial示例 3.2. Contacts 3.3. LDAP例子 3.4. CAS例子 3.5. Pre-Authentication例子 4. Spring Security社区 4.1. 任务跟踪 4.2. 成为参与者 4.3. 更多信息 II. 结构和实现 5. 技术概述 5.1. 运行环境 5.2. 核心组件 5.2.1. SecurityContextHolder, SecurityContext 和 Authentication对象 5.2.1.1. 获得当前用户的信息 5.2.2. UserDetailsService 5.2.3. GrantedAuthority 5.2.4. 小结 5.3. 验证 5.3.1. 什么是Spring Security的验证呢? 5.3.2. 直接设置SecurityContextHolder的内容 5.4. 在web应用中验证 5.4.1. ExceptionTranslationFilter 5.4.2. AuthenticationEntryPoint 5.4.3. 验证机制 5.4.4. 在请求之间保存SecurityContext。 5.5. Spring Security中的访问控制(验证) 5.5.1. 安全和AOP建议 5.5.2. 安全对象和AbstractSecurityInterceptor 5.5.2.1. 配置属性是什么? 5.5.2.2. RunAsManager 5.5.2.3. AfterInvocationManager 5.5.2.4. 扩展安全对象模型 5.6. 国际化 6. 核心服务 6.1. The AuthenticationManager, ProviderManager 和 AuthenticationProviders 6.1.1. DaoAuthenticationProvider 6.2. UserDetailsService实现 6.2.1. 内存认证 6.2.2. JdbcDaoImpl 6.2.2.1. 权限分组 6.3. 密码加密 6.3.1. 什么是散列加密? 6.3.2. 为散列加点儿盐 6.3.3. 散列和认证 III. web应用安全 7. 安全过滤器链 7.1. DelegatingFilterProxy 7.2. FilterChainProxy 7.2.1. 绕过过滤器链 7.3. 过滤器顺序 7.4. 使用其他过滤器 —— 基于框架 8. 核心安全过滤器 8.1. FilterSecurityInterceptor 8.2. ExceptionTranslationFilter 8.2.1. AuthenticationEntryPoint 8.2.2. AccessDeniedHandler 8.3. SecurityContextPersistenceFilter 8.3.1. SecurityContextRepository 8.4. UsernamePasswordAuthenticationFilter 8.4.1. 认证成功和失败的应用流程 9. Basic(基本)和Digest(摘要)验证 9.1. BasicAuthenticationFilter 9.1.1. 配置 9.2. DigestAuthenticationFilter 9.2.1. Configuration 10. Remember-Me认证 10.1. 概述 10.2. 简单基于散列标记的方法 10.3. 持久化标记方法 10.4. Remember-Me接口和实现 10.4.1. TokenBasedRememberMeServices 10.4.2. PersistentTokenBasedRememberMeServices 11. 会话管理 11.1. SessionManagementFilter 11.2. SessionAuthenticationStrategy 11.3. 同步会话 12. 匿名认证 12.1. 概述 12.2. 配置 12.3. AuthenticationTrustResolver IV. 授权 13. 验证架构 13.1. 验证 13.2. 处理预调用 13.2.1. AccessDecisionManager 13.2.2. 基于投票的AccessDecisionManager实现 13.2.2.1. RoleVoter 13.2.2.2. AuthenticatedVoter 13.2.2.3. Custom Voters 13.3. 处理后决定 14. 安全对象实现 14.1. AOP联盟 (MethodInvocation) 安全拦截器 14.1.1. 精确的 MethodSecurityIterceptor 配置 14.2. AspectJ (JoinPoint) 安全拦截器 15. 基于表达式的权限控制 15.1. 概述 15.1.1. 常用内建表达式 15.2. Web 安全表达式 15.3. 方法安全表达式 15.3.1. @Pre 和 @Post 注解 15.3.1.1. 访问控制使用 @PreAuthorize 和 @PostAuthorize 15.3.1.2. 过滤使用 @PreFilter 和 @PostFilter V. 高级话题 16. 领域对象安全(ACLs) 16.1. 概述 16.2. 关键概念 16.3. 开始 17. 预认证场景 17.1. 预认证框架类 17.1.1. AbstractPreAuthenticatedProcessingFilter 17.1.2. AbstractPreAuthenticatedAuthenticationDetailsSource 17.1.2.1. J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource 17.1.3. PreAuthenticatedAuthenticationProvider 17.1.4. Http403ForbiddenEntryPoint 17.2. 具体实现 17.2.1. 请求头认证(Siteminder) 17.2.1.1. Siteminder示例配置 17.2.2. J2EE容器认证 18. LDAP认证 18.1. 综述 18.2. 在Spring Security里使用LDAP 18.3. 配置LDAP服务器 18.3.1. 使用嵌入测试服务器 18.3.2. 使用绑定认证 18.3.3. 读取授权 18.4. 实现类 18.4.1. LdapAuthenticator实现 18.4.1.1. 常用功能 18.4.1.2. BindAuthenticator 18.4.1.3. PasswordComparisonAuthenticator 18.4.1.4. 活动目录认证 18.4.2. 链接到LDAP服务器 18.4.3. LDAP搜索对象 18.4.3.1. FilterBasedLdapUserSearch 18.4.4. LdapAuthoritiesPopulator 18.4.5. Spring Bean配置 18.4.6. LDAP属性和自定义UserDetails 19. JSP标签库 19.1. 声明Taglib 19.2. authorize标签 19.3. authentication 标签 19.4. accesscontrollist 标签 20. Java认证和授权服务(JAAS)供应器 20.1. 概述 20.2. 配置 20.2.1. JAAS CallbackHandler 20.2.2. JAAS AuthorityGranter 21. CAS认证 21.1. 概述 21.2. CAS是如何工作的 21.3. 配置CAS客户端 22. X.509认证 22.1. 概述 22.2. 把X.509认证添加到你的web系统中 22.3. 为tomcat配置SSL 23. 替换验证身份 23.1. 概述 23.2. 配置 A. 安全数据库表结构 A.1. User表 A.1.1. 组权限 A.2. 持久登陆(Remember-Me)表 A.3. ACL表 A.3.1. Hypersonic SQL A.3.1.1. PostgreSQL B. 安全命名空间 B.1. Web应用安全 - <http>元素 B.1.1. <http>属性 B.1.1.1. servlet-api-provision B.1.1.2. path-type B.1.1.3. lowercase-comparisons B.1.1.4. realm B.1.1.5. entry-point-ref B.1.1.6. access-decision-manager-ref B.1.1.7. access-denied-page B.1.1.8. once-per-request B.1.1.9. create-session B.1.2. <access-denied-handler> B.1.3. <intercept-url>元素 B.1.3.1. pattern B.1.3.2. method B.1.3.3. access B.1.3.4. requires-channel B.1.3.5. filters B.1.4. <port-mappings>元素 B.1.5. <form-login>元素 B.1.5.1. login-page B.1.5.2. login-processing-url B.1.5.3. default-target-url B.1.5.4. always-use-default-target B.1.5.5. authentication-failure-url B.1.5.6. authentication-success-handler-ref B.1.5.7. authentication-failure-handler-ref B.1.6. <http-basic>元素 B.1.7. <remember-me>元素 B.1.7.1. data-source-ref B.1.7.2. token-repository-ref B.1.7.3. services-ref B.1.7.4. token-repository-ref B.1.7.5. key属性 B.1.7.6. token-validity-seconds B.1.7.7. user-service-ref B.1.8. <session-management> 元素 B.1.8.1. session-fixation-protection B.1.9. <concurrent-control>元素 B.1.9.1. max-sessions属性 B.1.9.2. expired-url属性 B.1.9.3. error-if-maximum-exceeded属性 B.1.9.4. session-registry-alias和session-registry-ref属性 B.1.10. <anonymous>元素 B.1.11. <x509>元素 B.1.11.1. subject-principal-regex属性 B.1.11.2. user-service-ref属性 B.1.12. <openid-login>元素 B.1.13. <logout>元素 B.1.13.1. logout-url属性 B.1.13.2. logout-success-url属性 B.1.13.3. invalidate-session属性 B.1.14. <custom-filter>元素 B.2. 认证服务 B.2.1. <authentication-manager>元素 B.2.1.1. <authentication-provider>元素 B.2.1.2. 使用 <authentication-provider> 来引用一个 AuthenticationProvider Bean B.3. 方法安全 B.3.1. <global-method-security>元素 B.3.1.1. secured-annotations和jsr250-annotations属性 B.3.1.2. 安全方法使用<protect-pointcut> B.3.1.3. <after-invocation-provider> 元素 B.3.2. LDAP命名空间选项 B.3.2.1. 使用<ldap-server>元素定义LDAP服务器 B.3.2.2. <ldap-provider>元素 B.3.2.3. <ldap-user-service>元素

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值