- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试将 Spring security OAuth2 配置从 2.0.0.RC1 升级到 2.0.3.RELEASE。当时我从 sprklr 示例中复制了配置并使其工作。所以它基于基于 xml 的 Spring Security OAuth2 配置的工作示例。
现在,我已经升级到 Spring Security 最新版本(在撰写本文时为 2.0.3),并且还尝试将其转换为 java 配置。我在下面发布了 xml 配置和 java 配置。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd">
<!-- Authentication manager. -->
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select a.username, a.password, a.enabled, a.email from account a where a.username = ?"
authorities-by-username-query="select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?" />
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" pre-post-annotations="enabled" />
<security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager">
<security:intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<security:anonymous enabled="false" />
<security:http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request parameters -->
<security:custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
</security:http>
<security:http pattern="/api/.*/accounts" request-matcher="regex" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint" use-expressions="true">
<security:intercept-url pattern="/api/.*/accounts" method="POST" requires-channel="https" access="#oauth2.clientHasRole('ROLE_CLIENT') or hasRole('ROLE_ANONYMOUS')"/>
<security:intercept-url pattern="/.*" access="denyAll()" />
<security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
<security:expression-handler ref="oauthWebExpressionHandler" />
</security:http>
<security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager">
<security:anonymous enabled="false" />
<security:intercept-url pattern="/api/**" access="ROLE_USER,SCOPE_TRUST,SCOPE_PLAY"/>
<security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
</security:http>
<bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="*****" />
</bean>
<bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="*****/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<security:authentication-manager id="clientAuthenticationManager">
<security:authentication-provider user-service-ref="clientDetailsUserService" />
</security:authentication-manager>
<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" />
<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="tokenEnhancer" ref="tokenEnhancer" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
<property name="accessTokenValiditySeconds" value="6000" />
</bean>
<bean id="tokenEnhancer" class="com.****.*****.config.*****TokenEnhancer" />
<bean id="requestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
<constructor-arg name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="userApprovalHandler" class="com.****.*****.config.*****UserApprovalHandler">
<property name="approvalStore" ref="approvalStore" />
<property name="clientDetailsService" ref="clientDetails" />
<property name="requestFactory" ref="requestFactory" />
</bean>
<bean id="approvalStore" class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
<property name="tokenStore" ref="tokenStore" />
</bean>
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter" resource-id="*****" token-services-ref="tokenServices" />
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="*****-php-demo" secret="??????????"
authorized-grant-types="password,authorization_code,refresh_token,client_credentials"
authorities="ROLE_USER, ROLE_CLIENT"
scope="play,trust"
access-token-validity="6000"/>
<oauth:client client-id="*****-swagger-ui"
authorized-grant-types="implicit"
authorities="ROLE_USER, ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
scope="play,trust"
redirect-uri="${baseUrl}/o2c.html"
autoapprove="true"
access-token-validity="6000"/>
<oauth:client client-id="*****-runscope"
secret="???????????????????????????????"
authorized-grant-types="password,authorization_code,refresh_token"
authorities="ROLE_USER, ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
scope="play,trust"
redirect-uri="https://www.runscope.com/oauth_tool/callback"
autoapprove="true"
access-token-validity="6000"/>
</oauth:client-details-service>
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
和 java 配置(到目前为止..)
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
@Value("${baseUrl}") private String baseUrl;
@Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("*****-????????")
.secret("????????????????????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.and()
.withClient("*****-????????")
.authorizedGrantTypes("implicit")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris(baseUrl + "/o2c.html")
.autoApprove(true)
.and()
.withClient("*****-???????")
.secret("????????????????????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris("https://www.runscope.com/oauth_tool/callback")
.autoApprove(true);
return serviceConfig.clientDetailsService();
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
public DefaultTokenServices tokenServices() throws Exception {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setTokenEnhancer(new *****TokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
@Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
*****UserApprovalHandler handler = new *****UserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
return handler;
}
@Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Resource
private PasswordEncoder passwordEncoder;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Bean
protected UserDetailsService clientDetailsUserService() {
return new ClientDetailsUserDetailsService(clientDetailsService);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(clientDetailsUserService());
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
}
@Bean(name="authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("oauth2/client");
return entryPoint;
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/index.html", "/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.and()
.debug(true);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.anonymous().disable()
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
}
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerTokenServices tokenServices;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("*****");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous()
.disable();
// API calls
http
.authorizeRequests()
.regexMatchers(HttpMethod.POST, "/api/.*/accounts")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// API calls
http
.authorizeRequests()
.antMatchers("/api/**")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// @formatter:on
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private DefaultTokenServices tokenServices;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.clientDetailsService(clientDetailsService)
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler);
}
}
}
为此添加更多信息(根据 Dave Syer 的问题)
不生成 token ,请参阅下文了解更多信息。
要求:
curl -k -i -H "Accept: application/json" -X POST -d "grant_type=password&client_id=*****-php-demo&client_secret=???????&scope=play trust&username=tester&password=121212" https://localhost:8443/*****/oauth/token
响应:
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Cache-Control: no-store
Pragma: no-cache
WWW-Authenticate: Basic realm="*****/client", error="unauthorized", error_description="An Authentication object was not found in the SecurityContext"
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 16 Sep 2014 14:05:19 GMT
{"error":"unauthorized","error_description":"在 SecurityContext 中找不到身份验证对象"
服务器日志:
Request received for POST '/oauth/token':
org.apache.catalina.connector.RequestFacade@344dad0c
servletPath:
pathInfo:/oauth/token
headers:
user-agent: curl/7.30.0
host: localhost:8443
accept: application/json
content-length: 145
content-type: application/x-www-form-urlencoded
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
LogoutFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
(10 月 14 日更新)
Java安全配置;
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
@Value("${baseUrl}") private String baseUrl;
@Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("abc")
.secret("?????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.and()
.withClient("xyz")
.authorizedGrantTypes("implicit")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris(baseUrl + "/o2c.html")
.autoApprove(true)
.and()
.withClient("zzz")
.secret("?????????????????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris("https://www.runscope.com/oauth_tool/callback")
.autoApprove(true);
return serviceConfig.clientDetailsService();
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
public DefaultTokenServices tokenServices() throws Exception {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setTokenEnhancer(new MyTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
@Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
MyUserApprovalHandler handler = new MyUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
return handler;
}
@Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Resource
private PasswordEncoder passwordEncoder;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Bean
protected UserDetailsService clientDetailsUserService() {
return new ClientDetailsUserDetailsService(clientDetailsService);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
}
@Bean(name="authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager am = super.authenticationManagerBean();
return am;
}
@Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("redrum/client");
return entryPoint;
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.and()
.debug(true);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.anonymous().disable()
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
.and()
.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
}
@Bean
public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationEntryPoint(authenticationEntryPoint());
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerTokenServices tokenServices;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("xyz");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous()
.disable();
// API calls
http
.authorizeRequests()
.regexMatchers(HttpMethod.POST, "/api/.*/accounts")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// API calls
http
.authorizeRequests()
.antMatchers("/api/**")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// @formatter:on
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private DefaultTokenServices tokenServices;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.clientDetailsService(clientDetailsService)
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler);
}
}
}
最佳答案
这是解决方案;希望它对某人有用。使用 Spring OAuth2 文档和示例的当前状态,确定这个解决方案并不容易。
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
@Autowired
private ClientDetailsService clientDetailsService;
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
public DefaultTokenServices tokenServices() throws Exception {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setTokenEnhancer(new MyTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
@Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
MyUserApprovalHandler handler = new MyUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setUseApprovalStore(true);
return handler;
}
@Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${baseUrl}")
private String baseUrl;
@Autowired
private DataSource dataSource;
@Resource
private PasswordEncoder passwordEncoder;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("***-***-****")
.secret("???????????????????????????????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.and()
.withClient("***-******-**")
.authorizedGrantTypes("implicit")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris(baseUrl + "/o2c.html")
.autoApprove(true)
.and()
.withClient("******-***********")
.secret("???????????????????????????????????")
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("play", "trust")
.redirectUris("https://www.runscope.com/oauth_tool/callback")
.autoApprove(true);
return serviceConfig.clientDetailsService();
}
@Bean
UserDetailsService clientDetailsUserDetailsService() throws Exception {
return new ClientDetailsUserDetailsService(clientDetailsService());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
auth.userDetailsService(clientDetailsUserDetailsService());
}
@Bean(name="authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("app/client");
return entryPoint;
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.and()
.debug(true);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.anonymous().disable()
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.afterPropertiesSet();
http.addFilterBefore(filter, BasicAuthenticationFilter.class);
}
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerTokenServices tokenServices;
@Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
//resources.tokenServices(tokenServices);
resources.resourceId("app");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous()
.disable();
// API calls
http
.authorizeRequests()
.regexMatchers(HttpMethod.POST, "/api/.*/accounts")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// API calls
http
.authorizeRequests()
.antMatchers("/api/**")
.access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
.and()
//.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// @formatter:on
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private DefaultTokenServices tokenServices;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
AuthenticationEntryPoint authenticationEntryPoint;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint)
.realm("app/clients");
}
}
}
关于java - 升级 Spring Security OAuth2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25860198/
我有一个 webapp,它使用 php 服务器和数据库服务器执行大量 ajax 请求。我还创建了一个 iPhone 应用程序和一个 Android 应用程序,直到现在它们一直作为离线应用程序工作。 现
OAuth 的访问 token /刷新 token 流对我来说似乎非常不安全。帮助我更好地理解它。 假设我正在与利用 OAuth 的 API 集成(如 this one )。我有我的访问 token
这个问题在这里已经有了答案: 9年前关闭。 Possible Duplicate: How is oauth 2 different from oauth 1 我知道这两个不向后兼容。但是,既然已经实
我已经看到关于此的其他问题( here 、 here 和 here ),但我对任何解决方案都不满意,所以我再次询问。我正在启动一个 Web 应用程序,它将利用来自多个提供商(Google、Facebo
我知道(在 OAuth 中使用授权代码“授权代码”时),访问 token 的生命周期应该很短,但刷新 token 的生命周期可能很长。 所以我决定为我的项目: 访问 token 生命周期:1 天 刷新
在没有浏览器的情况下,我们可以在手机上的应用程序中使用 OAuth 吗? 如果没有浏览器,用户是否仍然可以批准 token 请求(以便消费者可以继续从服务提供者那里获取 protected 资源)?
用非常简单的术语来说,有人可以解释一下 OAuth 2 和 OAuth 1 之间的区别吗? OAuth 1 现在已经过时了吗?我们应该实现 OAuth 2 吗?我没有看到很多 OAuth 2 的实现;
修改表单例份验证登录过程并不难,因此除了正常的表单例份验证之外,WebClient 对象对由使用 Thinktecture IdentityModel 设置的 Web Api DAL 提供的 api/
我想连接到 LinkedIn 并通过他们的 API 提取一些信息。 LinkedIn API 使用 OAuth 2.0。 我读过的所有关于 OAuth 的文档(无论是在 LinkedIn 的上下文中还
OAuth 与其他身份验证标准的支持范围有多广? 这可能是社区维基的东西,但我还是要问。 我需要投资一些与服务器身份验证相关的东西,而且那里似乎有一些不错的东西。 最佳答案 OAuth 主要用作授权机
我有几个问题... 雅虎和微软 api 是否支持 oAuth 2.0? 如果是,那么主要是什么 应该采取的安全措施 转移时受到照顾 oAuth 1.0 到 oAuth 2.0。 Google API
我已经用谷歌 oAuth 开发了一个应用程序,这工作正常。 我可以登录并访问我的网站。 我的问题是,当我从我的应用程序中注销(注销)时,我删除了所有 session ,但未删除经过身份验证的 cook
我在 Internet 上寻找一些关于此的信息,最后在 RFC 上找到了 Oauth 1.0 协议(protocol):https://www.rfc-editor.org/rfc/rfc5849 您
我正在尝试制作 Google OpenID/OAuth hybrid签到工作。问题是它是一个可安装的网络(所以没有固定域),我也试图让它在我的开发机器上工作 - 所以返回 URL 类似于 http:/
我想构建一个独立与任何身份提供者(如 ADFS、OpenAM、oracle 身份)一起工作的应用程序。我的目的是验证来自任何一个 IDP 的登录用户,这些 IDP 配置为实现我的 SSO。 我不确定
我正在深入研究 Spring OAuth,发现一些相互矛盾的信息。 具体来说,this tutorial声明 /oauth/token 端点在将刷新 token 授予客户端应用程序之前处理用户名和密码
如何通过自定义命令行工具支持三足式 OAuth 工作流? 我想允许我的 CLI 工具的用户上网、登录并在本地缓存 token ,类似于 heroku login。正在做。 最佳答案 你必须扔掉同意屏幕
什么是 oauth 域?是否有任何免费的 oauth 服务?我可以将它用于 StackApps registration 吗? ?我在谷歌上搜索了很多,但找不到答案。 最佳答案 这是redirect_
我需要将我的 Delicious 书签下载到非 Web 应用程序,而无需持续的用户交互。我正在使用 Delicious 的 V2 API(使用 oAuth),但问题是他们的访问 token 似乎在一小
我正在尝试为两台服务器设置一个 nginx 负载均衡器/代理,并在两台服务器上运行 OAuth 身份验证的应用程序。 当 nginx 在端口 80 上运行时,一切都运行良好,但是当我将它放在任何其他端
我是一名优秀的程序员,十分优秀!