protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() //authorizerequests()方法有多个子方法,每个匹配器按照声明的顺序进行考虑。
.antMatchers("/resources/**", "/signup", "/about").permitAll() //我们指定了任意用户都可以访问的多个URL模式。
.antMatchers("/admin/**").hasRole("ADMIN") //任何以“/admin/”开头的URL将被限制为具有“ROLE_ADMIN”角色的用户。
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") //任何以“/db/”开头的URL都要求用户同时具有“ROLE_ADMIN”和“ROLE_DBA”。
.anyRequest().authenticated() //任何尚未匹配的URL只需要对用户进行身份验证
.and()
.formLogin()
.loginPage("/login") //更新的配置指定登录页的位置。
.permitAll(); //permitall()方法允许为与基于表单的登录相关联的所有url授予所有用户访问权限。
.logout() //提供注销的支持。这是在使用WebSecurityConfigurerAdapter时自动应用的。
.logoutUrl("/test/logout") //触发注销发生的URL(默认为 /logout)。如果启用了CSRF保护(默认),那么请求也必须是POST。
.logoutSuccessUrl("/test/index") //注销后要重定向到的URL。默认是/login?logout。
.logoutSuccessHandler(logoutSuccessHandler) //让我们指定一个自定义logoutsuccessesshandler。如果指定了此参数,则忽略logoutSuccessUrl()。
.invalidateHttpSession(true) //指定在注销时是否使HttpSession无效。这在默认情况下是正确的。
.addLogoutHandler(logoutHandler) //添加一个LogoutHandler。默认情况下,SecurityContextLogoutHandler被添加为最后一个LogoutHandler。
.deleteCookies(cookieNamesToClear) //允许在注销成功时指定要删除的cookie的名称。这是显式添加CookieClearingLogoutHandler的快捷方式。
.and()
...
}
org.springframework.security
spring-security-bom
5.1.3.RELEASE
pom
import
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Client()
.clientRegistrationRepository(this.clientRegistrationRepository())
.authorizedClientRepository(this.authorizedClientRepository())
.authorizedClientService(this.authorizedClientService())
.authorizationCodeGrant()
.authorizationRequestRepository(this.authorizationRequestRepository())
.authorizationRequestResolver(this.authorizationRequestResolver())
.accessTokenResponseClient(this.accessTokenResponseClient());
}
}
ClientRegistration:客户端注册
public final class ClientRegistration {
private String registrationId; //唯一标识ClientRegistration(客户注册)的ID。
private String clientId; //客户端标识符
private String clientSecret; //客户端秘钥
private ClientAuthenticationMethod clientAuthenticationMethod; //使用提供程序对客户端进行身份验证的方法
private AuthorizationGrantType authorizationGrantType; //OAuth 2.0授权框架定义了四种授权授权类型。支持的值是authorization_code、隐式值和client_credentials。
private String redirectUriTemplate; //在最终用户对客户机进行了身份验证和授权访问之后,授权服务器将客户机注册的重定向URI重定向到终端用户的用户代理。
private Set scopes; //客户端在授权请求流(如openid、电子邮件或配置文件)期间请求的范围。
private ProviderDetails providerDetails;
private String clientName; //用于客户端的描述性名称。该名称可用于某些场景,例如在自动生成的登录页面中显示客户端名称时。
public class ProviderDetails {
private String authorizationUri; //授权服务器的授权端点URI。
private String tokenUri; //授权服务器的令牌端点URI。
private UserInfoEndpoint userInfoEndpoint;
private String jwkSetUri; //用于从授权服务器检索JSON Web Key (JWK)集的URI,其中包含用于验证ID令牌的JSON Web签名(JWS)和可选的UserInfo响应的加密密钥。
private Map configurationMetadata; //OpenID提供程序配置信息。此信息仅在Spring Boot 2中可用。
public class UserInfoEndpoint {
private String uri; //用于访问经过身份验证的最终用户的声明/属性的UserInfo端点URI。
private AuthenticationMethod authenticationMethod; //将访问令牌发送到UserInfo端点时使用的身份验证方法。支持的值是头、表单和查询。
private String userNameAttributeName; //UserInfo响应中返回的属性的名称,该属性引用最终用户的名称或标识符。
}
}
}
ClientRegistrationRepository:ClientRegistrationRepository用作OAuth 2.0的存储库
spring.security.oauth2.client.registration.[registrationId]
的实例,然后将其组合为 ClientRegistration instance(s) within a ClientRegistrationRepository.
OAuth2AuthorizedClient: 授权客户端
OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService
@Controller
public class OAuth2LoginController {
@Autowired
private OAuth2AuthorizedClientService authorizedClientService;
@RequestMapping("/userinfo")
public String userinfo(OAuth2AuthenticationToken authentication) {
// authentication.getAuthorizedClientRegistrationId() returns the
// registrationId of the Client that was authorized during the oauth2Login() flow
OAuth2AuthorizedClient authorizedClient =
this.authorizedClientService.loadAuthorizedClient(
authentication.getAuthorizedClientRegistrationId(),
authentication.getName());
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
...
return "userinfo";
}
}
RegisteredOAuth2AuthorizedClient:
@Controller
public class OAuth2LoginController {
@RequestMapping("/userinfo")
public String userinfo(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) {
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
...
return "userinfo";
}
}
AuthorizationRequestRepository:
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Client()
.authorizationCodeGrant()
.authorizationRequestRepository(this.cookieAuthorizationRequestRepository())
...
}
private AuthorizationRequestRepository cookieAuthorizationRequestRepository() {
return new HttpCookieOAuth2AuthorizationRequestRepository();
}
}
OAuth2AuthorizationRequestResolver: 从提供的web请求中解析一个OAuth2AuthorizationRequest。
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.authorizationEndpoint()
.authorizationRequestResolver(
new CustomAuthorizationRequestResolver(
this.clientRegistrationRepository)); //配置自定义OAuth2AuthorizationRequestResolver
}
}
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private final OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver;
public CustomAuthorizationRequestResolver(
ClientRegistrationRepository clientRegistrationRepository) {
this.defaultAuthorizationRequestResolver =
new DefaultOAuth2AuthorizationRequestResolver(
clientRegistrationRepository, "/oauth2/authorization");
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(request); //尝试使用DefaultOAuth2AuthorizationRequestResolver解析OAuth2AuthorizationRequest
return authorizationRequest != null ? //如果OAuth2AuthorizationRequest被解析,则返回定制的版本,否则返回null
customAuthorizationRequest(authorizationRequest) :
null;
}
@Override
public OAuth2AuthorizationRequest resolve(
HttpServletRequest request, String clientRegistrationId) {
OAuth2AuthorizationRequest authorizationRequest =
this.defaultAuthorizationRequestResolver.resolve(
request, clientRegistrationId); //尝试使用DefaultOAuth2AuthorizationRequestResolver解析OAuth2AuthorizationRequest
return authorizationRequest != null ? //如果OAuth2AuthorizationRequest被解析,则返回定制的版本,否则返回null
customAuthorizationRequest(authorizationRequest) :
null;
}
private OAuth2AuthorizationRequest customAuthorizationRequest(
OAuth2AuthorizationRequest authorizationRequest) {
Map additionalParameters =
new LinkedHashMap<>(authorizationRequest.getAdditionalParameters());
additionalParameters.put("prompt", "consent"); //向现有的OAuth2AuthorizationRequest.additionalParameters添加自定义参数
return OAuth2AuthorizationRequest.from(authorizationRequest) //创建默认OAuth2AuthorizationRequest的副本,该副本返回一个OAuth2AuthorizationRequest。进一步修改的构建器
.additionalParameters(additionalParameters) //覆盖默认的additionalParameters
.build();
}
}
private OAuth2AuthorizationRequest customAuthorizationRequest(
OAuth2AuthorizationRequest authorizationRequest) {
String customAuthorizationRequestUri = UriComponentsBuilder
.fromUriString(authorizationRequest.getAuthorizationRequestUri())
.queryParam("prompt", "consent")
.build(true)
.toUriString();
return OAuth2AuthorizationRequest.from(authorizationRequest)
.authorizationRequestUri(customAuthorizationRequestUri)
.build();
}
OAuth2AccessTokenResponseClient: OAuth2AccessTokenResponseClient的主要角色是在授权服务器的令牌端点将授权授予凭据交换为访问令牌凭据。
RestTemplate restTemplate = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),//当发送OAuth 2.0访问令牌请求时,需要使用Spring MVC FormHttpMessageConverter。
new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
OAuth2AccessTokenResponseHttpMessageConverter是OAuth 2.0访问令牌响应的HttpMessageConverter。您可以提供
带有自定义的OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()
Converter
OAuth2ErrorResponseErrorHandler是一个ResponseErrorHandler,它可以处理OAuth 2.0错误(400个错误请求)。它使用一个
OAuth2ErrorHttpMessageConverter 用于将OAuth 2.0错误参数转换为OAuth2Error。
@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Client()
.authorizationCodeGrant()
.accessTokenResponseClient(this.customAccessTokenResponseClient())
...
}
private OAuth2AccessTokenResponseClient customAccessTokenResponseClient() {
...
}
}
获取授权服务器的clientId,clientSecret
设置重定向URL
{baseUrl}/login/oauth2/code/{registrationId}
. The registrationId is a unique identifier for the ClientRegistration.application.yml文件配置
spring:
security:
oauth2:
client:
registration: //OAuth客户端属性的基本属性前缀
google: //在基本属性前缀后面是客户机注册的ID,比如谷歌。( registrationId (google) matches the GOOGLE enum (case-insensitive))
client-id: google-client-id
client-secret: google-client-secret
Spring Boot 2.x Property Mappings:
Spring Boot 2.x | ClientRegistration |
---|---|
spring.security.oauth2.client.registration.[registrationId] | registrationId |
spring.security.oauth2.client.registration.[registrationId].client-id | clientId |
spring.security.oauth2.client.registration.[registrationId].client-secret | clientSecret |
spring.security.oauth2.client.registration.[registrationId].client-authentication-method | clientAuthenticationMethod |
spring.security.oauth2.client.registration.[registrationId].authorization-grant-type | authorizationGrantType |
spring.security.oauth2.client.registration.[registrationId].redirect-uri | redirectUriTemplate |
spring.security.oauth2.client.registration.[registrationId].scope | scopes |
spring.security.oauth2.client.registration.[registrationId].client-name | clientName |
spring.security.oauth2.client.provider.[providerId].authorization-uri | providerDetails.authorizationUri |
spring.security.oauth2.client.provider.[providerId].token-uri | providerDetails.tokenUri |
spring.security.oauth2.client.provider.[providerId].jwk-set-uri | providerDetails.jwkSetUri |
spring.security.oauth2.client.provider.[providerId].user-info-uri | providerDetails.userInfoEndpoint.uri |
spring.security.oauth2.client.provider.[providerId].user-info-authentication-method | providerDetails.userInfoEndpoint.authenticationMethod |
spring.security.oauth2.client.provider.[providerId].userNameAttribute | providerDetails.userInfoEndpoint.userNameAttributeName |
CommonOAuth2Provider:Oauth2.0 服务提供者
配置自定义Provider属性
重写 Spring Boot 2.x Auto-configuration
OAuth2ClientAutoConfiguration
.
@Configuration
public class OAuth2LoginConfig {
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
}
private ClientRegistration googleClientRegistration() {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build();
}
}
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
@Configuration
public class OAuth2LoginConfig {
@EnableWebSecurity
public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
}
private ClientRegistration googleClientRegistration() {
return ClientRegistration.withRegistrationId("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("openid", "profile", "email", "address", "phone")
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
.userNameAttributeName(IdTokenClaimNames.SUB)
.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
.clientName("Google")
.build();
}
}
@EnableWebSecurity
public class MultiHttpSecurityConfig {
@Bean //正常配置身份验证
public UserDetailsService userDetailsService() throws Exception {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("user").password("password").roles("USER").build());
manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
return manager;
}
@Configuration
@Order(1) //创建一个包含@Order的WebSecurityConfigurerAdapter实例,以指定应该首先考虑哪个WebSecurityConfigurerAdapter。
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") //http.antMatcher声明此HttpSecurity只适用于以/api/开头的url
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration //创建WebSecurityConfigurerAdapter的另一个实例。如果URL不以/api/开头,将使用此配置。这个配置是在ApiWebSecurityConfigurationAdapter之后考虑的,因为它在1之后有一个@Order值(没有@Order默认值是last)。
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
// ...
}
public interface BankService {
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();
@Secured("ROLE_TELLER")
public Account post(Account account, double amount);
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
// ... create and return custom MethodSecurityExpressionHandler ...
return expressionHandler;
}
}
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Login()
.clientRegistrationRepository(this.clientRegistrationRepository())
.authorizedClientRepository(this.authorizedClientRepository())
.authorizedClientService(this.authorizedClientService())
.loginPage("/login/oauth2")//您需要提供一个具有@RequestMapping("/login/oauth2")的@Controller,该映射能够呈现自定义登录页面。
.authorizationEndpoint()//授权端点:客户机用于通过用户代理重定向从资源所有者获得授权。
.baseUri(this.authorizationRequestBaseUri())
.authorizationRequestRepository(this.authorizationRequestRepository())
.authorizationRequestResolver(this.authorizationRequestResolver())
.and()
.redirectionEndpoint()//授权服务器使用重定向端点通过资源所有者user-agent将授权响应(包含授权凭据)返回给客户机。
.baseUri(this.authorizationResponseBaseUri())//OAuth 2.0登录利用授权代码授予。因此,授权凭证就是授权代码。
.and()
.tokenEndpoint()//令牌端点:客户端用于交换访问令牌的授权授予,通常使用客户端身份验证。
.accessTokenResponseClient(this.accessTokenResponseClient())
.and()
.userInfoEndpoint()
.userAuthoritiesMapper(this.userAuthoritiesMapper())
.userService(this.oauth2UserService())
.oidcUserService(this.oidcUserService())
.customUserType(GitHubOAuth2User.class, "github");
}
}
return CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id")
.clientSecret("google-client-secret")
.redirectUriTemplate("{baseUrl}/login/oauth2/callback/{registrationId}")
.build();
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Login()
.userInfoEndpoint()
.userAuthoritiesMapper(this.userAuthoritiesMapper())
...
}
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set mappedAuthorities = new HashSet<>();
authorities.forEach(authority -> {
if (OidcUserAuthority.class.isInstance(authority)) {
OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;
OidcIdToken idToken = oidcUserAuthority.getIdToken();
OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
// Map the claims found in idToken and/or userInfo
// to one or more GrantedAuthority's and add it to mappedAuthorities
} else if (OAuth2UserAuthority.class.isInstance(authority)) {
OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
Map userAttributes = oauth2UserAuthority.getAttributes();
// Map the attributes found in userAttributes
// to one or more GrantedAuthority's and add it to mappedAuthorities
}
});
return mappedAuthorities;
};
}
}
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login();
}
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
...
}
}
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Login()
.userInfoEndpoint()
.customUserType(GitHubOAuth2User.class, "github")
...
}
}
public class GitHubOAuth2User implements OAuth2User {
private List authorities =
AuthorityUtils.createAuthorityList("ROLE_USER");
private Map attributes;
private String id;
private String name;
private String login;
private String email;
@Override
public Collection extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public Map getAttributes() {
if (this.attributes == null) {
this.attributes = new HashMap<>();
this.attributes.put("id", this.getId());
this.attributes.put("name", this.getName());
this.attributes.put("login", this.getLogin());
this.attributes.put("email", this.getEmail());
}
return attributes;
}
省略getter、setter方法
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.oauth2Login()
.userInfoEndpoint()
.userService(this.oauth2UserService())
...
}
private OAuth2UserService oauth2UserService() {
...
}
}
现在我们已经对Spring安全体系结构及其核心类有了一个高层次的概述,接下来让我们更仔细地研究一两个核心接口及其实现,特别是AuthenticationManager、UserDetailsService和AccessDecisionManager。在本文档的其余部分中,这些内容会定期出现,因此了解它们的配置和操作方式非常重要。
The AuthenticationManager, ProviderManager and AuthenticationProvider
DaoAuthenticationProvider
UserDetailsService Implementations
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
In-Memory Authentication
String idForEncode = "bcrypt";
Map encoders = new HashMap<>();
encoders.put(idForEncode, new BCryptPasswordEncoder());
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("sha256", new StandardPasswordEncoder());
PasswordEncoder passwordEncoder =
new DelegatingPasswordEncoder(idForEncode, encoders);
{id}encodedPassword
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG //密码编解码器id为bcrypt,匹配时将委托给BCryptPasswordEncoder
{noop}password //密码将具有noop的PasswordEncoder id和encodedPassword的password。匹配时将委托给NoOpPasswordEncoder
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc //密码编解码器id为pbkdf2,匹配时将委托给Pbkdf2PasswordEncoder
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= //密码为scrypt的PasswordEncoder 匹配时委托给scryptpasswordender
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 //密码为sha256,匹配时将委托给StandardPasswordEncoder
// Create an encoder with strength 16
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
// Create an encoder with all the defaults
Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder();
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
// Create an encoder with all the defaults
SCryptPasswordEncoder encoder = new SCryptPasswordEncoder();
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));
bcrypt - BCryptPasswordEncoder (Also used for encoding)
ldap - LdapShaPasswordEncoder
MD4 - Md4PasswordEncoder
MD5 - new MessageDigestPasswordEncoder("MD5")
noop - NoOpPasswordEncoder
pbkdf2 - Pbkdf2PasswordEncoder
scrypt - SCryptPasswordEncoder
SHA-1 - new MessageDigestPasswordEncoder("SHA-1")
SHA-256 - new MessageDigestPasswordEncoder("SHA-256")
sha256 - StandardPasswordEncoder
public interface SecurityContextRepository {
SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);
void saveContext(SecurityContext context, HttpServletRequest request,
HttpServletResponse response);
}