Spring Security Reference 部分翻译
来源:互联网 发布:java后端需要学什么 编辑:程序博客网 时间:2024/05/16 19:13
本文为个人学习spring security 是对官方技术文档的个人翻译,以便学习使用。原文链接http://docs.spring.io/spring-security/site/docs/4.1.2.BUILD-SNAPSHOT/reference/htmlsingle/#samples
5. Java Configuration(java配置文件)
在Spring3.1版本的时候就支持使用java配置文件的方式。从Spring Security 3.2开始 就可以用配置的方式轻松的配置Spring Security到项目中而不需要使用xml 的方式。
General support for Java Configuration was added to Spring framework in Spring 3.1. Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.如果你对第6章使用安全空间方式配置,那么你应该可以很轻松的找到他们之间的很多相似之处。
If you are familiar with the Chapter 6, Security Namespace Configuration then you should find quite a few similarities between it and the Security Java Configuration support.
Spring Security 提供了很多简单的以jc结尾的使用Spring Security java配置的说明。
Spring Security provides lots of sample applications that end in -jc which demonstrate the use of Spring Security Java Configuration.
5.1 Hello Web Security Java Configuration
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.*;import org.springframework.security.config.annotation.authentication.builders.*;import org.springframework.security.config.annotation.web.configuration.*;@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");}}
这个方法的名字‘configureGlobal ’ 并不重要,但是重要的是他的类以注解(@EnableWebSecurity, @EnableGlobalMethodSecurity, or @EnableGlobalAuthentication.)的方式配置了 AuthenticationManagerBuilder类。否则会有不可预测的结果。
The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either @EnableWebSecurity, @EnableGlobalMethodSecurity, or @EnableGlobalAuthentication.Doing otherwise has unpredictable results.
这个配置文件并不多,但是他做了很多的事:
There really isn’t much to this configuration, but it does a lot. You can find a summary of the features below:
- 对程序中的每一个URL进行验证。
- Require authentication to every URL in your application
- 为你生成一个登陆界面
- Generate a login form for you
- 允许以用户名为user和密码为password的基于报单方式的验证。
- Allow the user with the Username user and the Password password to authenticate with form based authentication
- 允许用户注销
- Allow the user to logout
- CSRF攻击防范
- CSRF attack prevention
- 会话固定保护
- Session Fixation protection
- 安全头一体化
Security Header integration
- HTTP Strict Transport Security for secure requests
- X-Content-Type-Options integration
- Cache Control (can be overridden later by your application to allow caching of your static resources)
- X-XSS-Protection integration
- X-Frame-Options integration to help prevent Clickjacking
Integrate with the following Servlet API methods
- HttpServletRequest#getRemoteUser()
- HttpServletRequest.html#getUserPrincipal()
- HttpServletRequest.html#isUserInRole(java.lang.String)
- HttpServletRequest.html#login(java.lang.String, java.lang.String)
- HttpServletRequest.html#logout()
5.1.1 AbstractSecurityWebApplicationInitializer
如果你并没有使用Spring 或者Spring MVC,你需要确定WebSecurityConfig的父类已经加载了它。你可以通过下面的例子看到:
If you are not using Spring or Spring MVC, you will need to pass in the WebSecurityConfig into the superclass to ensure the configuration is picked up. You can find an example below:import org.springframework.security.web.context.*;public class SecurityWebApplicationInitializerextends AbstractSecurityWebApplicationInitializer {public SecurityWebApplicationInitializer() {super(WebSecurityConfig.class);}}
这个SecurityWebApplicationInitializer的类做了一下的几个工作:
The SecurityWebApplicationInitializer will do the following things:
- 自动为你的程序里的每一个URL注册 springSecurityFilterChain Filter
- Automatically register the springSecurityFilterChain Filter for every URL in your application
- 加载 WebSecurityConfig时添加ContextLoaderListener
- Add a ContextLoaderListener that loads the WebSecurityConfig.
5.1.3 AbstractSecurityWebApplicationInitializer with Spring MVC
import org.springframework.security.web.context.*;public class SecurityWebApplicationInitializerextends AbstractSecurityWebApplicationInitializer {}
这个仅仅是为我们应用程序的每一个URL注册到springSecurityFilterChain Filter。之后我们要确定WebSecurityConfig已经加载到了我们已经存在的应用程序中。例如我们使用SpringMVC 它将会在getRootConfigClasses()中加入。
This would simply only register the springSecurityFilterChain Filter for every URL in your application. After that we would ensure that WebSecurityConfig was loaded in our existing ApplicationInitializer. For example, if we were using Spring MVC it would be added in the getRootConfigClasses()public class MvcWebApplicationInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[] { WebSecurityConfig.class };}// ... other overrides ...}
5.2 HttpSecurity
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();}
上面的默认配置:
确保对我们的应用程序的任何请求都要求用户进行身份验证
允许用户以form 为基础的登录进行身份验证
允许用户验证的HTTP基本认证
The default configuration above:
- Ensures that any request to our application requires the user to be authenticated
- Allows users to authenticate with form based login
- Allows users to authenticate with HTTP Basic authentication
<http><intercept-url pattern="/**" access="authenticated"/><form-login /><http-basic /></http>
5.3 Java Configuration and Form Login
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login") .permitAll(); }
The updated configuration specifies the location of the log in page.更新配置指定了登录界面
We must grant all users (i.e. unauthenticated users) access to our log in page. The formLogin().permitAll() method allows granting access to all users for all URLs associated with form based log in.
我们必须为那些想要访问登录界面的所有用户放行。<c:url value="/login" var="loginUrl"/><form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <p>Invalid username and password.</p></c:if><c:if test="${param.logout != null}"> <p>You have been logged out.</p></c:if><p><label for="username">Username</label><input type="text" id="username" name="username"/></p><p><label for="password">Password</label><input type="password" id="password" name="password"/></p><input type="hidden" name="${_csrf.parameterName}"value="${_csrf.token}"/><button type="submit" class="btn">Log in</button></form>
A POST to the /login
URL will attempt to authenticate the user
If the query parameter error
exists, authentication was attempted and failed
If the query parameter logout
exists, the user was successfully logged out
The username must be present as the HTTP parameter named username
The password must be present as the HTTP parameter named password
We must Section 18.4.3, “Include the CSRF Token” To learn more read the Chapter 18, Cross Site Request Forgery (CSRF) section of the reference
5.4 Authorize Requests 请求授权
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated() .and()// ....formLogin();}
There are multiple children to the http.authorizeRequests() method each matcher is considered in the order they were declared. 在http.authorizeRequests()方法中有多个子标签,并已他们声明的顺序进行匹配
We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
我们指定了多个用户可以访问的URL,具体来说就以 "/resources/", equals "/signup", or equals "/about"开头的访问
Any URL that starts with "/admin/" will be resticted to users who have the role "ROLE_ADMIN". You will notice that since we are invoking the hasRole method we do not need to specify the "ROLE_" prefix.
任何访问/admin/ 的URL都必须具有ADMIN的角色,你可以看到因为我们使用了hasRole()方法,所以我们不用添加“ROLE_”前缀。
Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". You will notice that since we are using the hasRole expression we do not need to specify the "ROLE_" prefix.
Any URL that has not already been matched on only requires that the user be authenticated
没有匹配的其他网址只需要进行用户验证
5.5 Handling Logouts
When using the WebSecurityConfigurerAdapter, logout capabilities are automatically applied. The default is that accessing the URL/logout
will log the user out by:当我们使用自动应用的websecurityconfigureradapter注销功能时,默认会链接到将会使我们登出的URL页面,登出的布置如下
- Invalidating the HTTP Session
- Cleaning up any RememberMe authentication that was configured
- Clearing the
SecurityContextHolder
- Redirect to
/login?logout
清理任何配置记得认证
清理securitycontextholder
重定向到/登录?注销
protected void configure(HttpSecurity http) throws Exception {http.logout() .logoutUrl("/my/logout") .logoutSuccessUrl("/my/index") .logoutSuccessHandler(logoutSuccessHandler) .invalidateHttpSession(true) .addLogoutHandler(logoutHandler) .deleteCookies(cookieNamesToClear) .and()...}
Provides logout support. This is automatically applied when using WebSecurityConfigurerAdapter
.
提供注销的支持
The URL that triggers log out to occur (default is /logout
). If CSRF protection is enabled (default), then the request must also be a POST. For for information, please consult the JavaDoc.
该URL指向注销页面(默认为/logout页面),默认提供CSRF保护功能,但必须是POST方法,获取更多信息请查询文档。
The URL to redirect to after logout has occurred. The default is /login?logout
. For for information, please consult the JavaDoc.
注销成功后指向的页面
Let’s you specify a custom LogoutSuccessHandler
. If this is specified, logoutSuccessUrl()
is ignored. For for information, please consult the JavaDoc.
Specify whether to invalidate the HttpSession
at the time of logout. This is true by default. Configures the SecurityContextLogoutHandler
under the covers. For for information, please consult the JavaDoc
是否注销session,默认是.
Adds a LogoutHandler
. SecurityContextLogoutHandler
is added as the last LogoutHandler
by default.
Allows specifying the names of cookies to be removed on logout success. This is a shortcut for adding a CookieClearingLogoutHandler
explicitly.
5.5.1 LogoutHandler
Generally, LogoutHandler implementations indicate classes that are able to participate in logout handling. They are expected to be invoked to perform necessary cleanup. As such they should not throw exceptions. Various implementations are provided:- PersistentTokenBasedRememberMeServices
- TokenBasedRememberMeServices
- CookieClearingLogoutHandler
- CsrfLogoutHandler
- SecurityContextLogoutHandler
5.5.2 LogoutSuccessHandler
The LogoutSuccessHandler
is called after a successful logout by the LogoutFilter
, to handle e.g. redirection or forwarding to the appropriate destination. Note that the interface is almost the same as the LogoutHandler
but may raise an exception.
The following implementations are provided:
- SimpleUrlLogoutSuccessHandler
- HttpStatusReturningLogoutSuccessHandler
As mentioned above, you don’t need to specify the SimpleUrlLogoutSuccessHandler
directly. Instead, the fluent API provides a shortcut by setting thelogoutSuccessUrl()
. This will setup the SimpleUrlLogoutSuccessHandler
under the covers. The provided URL will be redirected to after a logout has occurred. The default is /login?logout
.
The HttpStatusReturningLogoutSuccessHandler
can be interesting in REST API type scenarios. Instead of redirecting to a URL upon the successful logout, thisLogoutSuccessHandler
allows you to provide a plain HTTP status code to be returned. If not configured a status code 200 will be returned by default.
5.5.3 Further Logout-Related References
- Logout Handling
- Testing Logout
- HttpServletRequest.logout()
- Section 17.4, “Remember-Me Interfaces and Implementations”
- Logging Out in section CSRF Caveats
- Section Single Logout (CAS protocol)
- Documentation for the logout element in the Spring Security XML Namespace section
5.6 Authentication
5.6.1 In Memory Authentication
We have already seen an example of configuring in memory authentication for a single user. Below is an example to configure multiple users:@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("USER", "ADMIN");}
5.6.2 JDBC Authentication
DataSource
within your application. Thejdbc-javaconfig sample provides a complete example of using JDBC based authentication.@Autowiredprivate DataSource dataSource;@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("USER", "ADMIN");}
5.6.3 LDAP Authentication
You can find the updates to suppport LDAP based authentication. The ldap-javaconfig sample provides a complete example of using LDAP based authentication.
@Autowiredprivate DataSource dataSource;@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.ldapAuthentication().userDnPatterns("uid={0},ou=people").groupSearchBase("ou=groups");}
dn: ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: organizationalUnitou: groupsdn: ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: organizationalUnitou: peopledn: uid=admin,ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: personobjectclass: organizationalPersonobjectclass: inetOrgPersoncn: Rod Johnsonsn: Johnsonuid: adminuserPassword: passworddn: uid=user,ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: personobjectclass: organizationalPersonobjectclass: inetOrgPersoncn: Dianne Emusn: Emuuid: useruserPassword: passworddn: cn=user,ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: groupOfNamescn: useruniqueMember: uid=admin,ou=people,dc=springframework,dc=orguniqueMember: uid=user,ou=people,dc=springframework,dc=orgdn: cn=admin,ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: groupOfNamescn: adminuniqueMember: uid=admin,ou=people,dc=springframework,dc=org
- Spring Security Reference 部分翻译
- spring boot security reference
- Spring Security Reference-1
- Spring Security Architecture翻译
- Spring Security 部分配置
- Spring Framework Reference Documentation翻译
- Spring Security教程第二部分-工程里添加spring-security
- Spring Framework 2.0 Reference翻译项目过半
- Helloworld Spring Security Java config页面翻译
- Spring security --- Acegi部分配置信息
- Spring Security使用总结(基础部分)
- Spring Security教程第五部分-数据库连接登录
- Spring Framework 2.0 Reference翻译项目正式启动
- Spring Framework 2.0 Reference翻译项目顺利完成
- Spring 4.x Reference翻译(一)IOC容器
- spring-framework-reference翻译 22 Web MVC framework
- Spring相关文档翻译-chapter9(AOP部分)
- Spring Security-3.0.1中文官方文档(翻译版)
- 天纵智能软件快速开发平台网格编辑插件
- C++虚函数
- Java-Collection集合总结
- 8张Linux思维导图(定位自己能力、清楚学习方向)
- ubuntu给手机建wifi
- Spring Security Reference 部分翻译
- Session的监听以及单点登录整合
- HDU 4183 最大流模板题
- DropdownList绑定的两种方法
- 培训总结集_(不更新)
- M - 确定比赛名次
- JavaScript基础知识(一)
- 什么是交叉编译?
- 结构体struct && 联合union