i_r*_*aqz 9 java oauth-2.0 spring-boot
我已将Spring Boot应用程序配置为提供oauth2授权.
@Configuration
public class OAuth2Configuration {
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
@Autowired
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.logout()
.logoutUrl("/oauth/logout")
.logoutSuccessHandler(customLogoutSuccessHandler)
.and()
.csrf()
.disable()
.headers()
.frameOptions().disable()
.exceptionHandling().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/v1/login/**").permitAll()
.antMatchers("/api/v1/admin/**").permitAll()
.antMatchers("/api/v1/test/**").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/api/**").authenticated();
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
private static final String ENV_OAUTH = "authentication.oauth.";
private static final String PROP_CLIENTID = "clientid";
private static final String PROP_SECRET = "secret";
private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
private RelaxedPropertyResolver propertyResolver;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(propertyResolver.getProperty(PROP_CLIENTID))
.scopes("read", "write")
.authorities(Authorities.ROLE_USER.name())
.authorizedGrantTypes("password", "refresh_token", "authorization_code", "implicit")
.secret(propertyResolver.getProperty(PROP_SECRET))
.accessTokenValiditySeconds(
propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800))
.refreshTokenValiditySeconds(100000);
}
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
}
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public CustomPasswordEncoder passwordEncoder() {
return new CustomPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**").antMatchers("/api/login/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName("WebServices").and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().requestMatchers()
.antMatchers("/oauth/authorize").and().authorizeRequests().antMatchers("/oauth/authorize")
.authenticated();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
}
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private AccountDao accountDao;
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
Account userFromDatabase = null;
String lowercaseLogin = login.toLowerCase();
if (lowercaseLogin.contains("@")) {
userFromDatabase = accountDao.getByEmailId(lowercaseLogin);
} else {
userFromDatabase = accountDao.getByPhoneNumber(lowercaseLogin);
}
if (userFromDatabase != null) {
if (!userFromDatabase.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = userFromDatabase.getRoles().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getRoleName())).collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(userFromDatabase.getAccountName(),
userFromDatabase.getAccountPassword(), grantedAuthorities);
} else {
throw new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database");
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在每当我在访问令牌到期后尝试获取刷新令牌时,我总是得到
2017-07-10 00:57:40.797 INFO 68115 --- [nio-9090-exec-4] ossoprovider.endpoint.TokenEndpoint:处理错误:NoSuchClientException,没有请求id的客户端:12345678
虽然数据库中有一行,列电话号码为12345678,帐户名称为12345678.
我有标题设置为授权:基本xxx xxx与我用来获取access_token相同,所以我假设它工作正常.
但输出总是如此
{"error":"unauthorized","error_description":"在数据库中找不到用户12345678"}
你应该传递的clientId和客户端密钥(这是从不同的用户id和密码获取时间)access token使用refresh token。不确定在authorisation标题中传递了什么。
你似乎有两个不同的问题。什么时候出现以下错误:
{ "error": "unauthorized", "error_description": "在数据库中未找到用户 12345678" }
您能否验证用户是否已成功通过身份验证以及服务是否返回访问令牌和刷新令牌?您可以将调试指针放入UserDetailsService并检查流程。
尝试按照以下步骤验证配置:
获取刷新令牌,假设您正在使用
curl -vu clientId:clientSecret 'http://your_domain_url/api/oauth/token?username=userName&password=password&grant_type=password'
Run Code Online (Sandbox Code Playgroud)
这里用户名和密码与客户端 ID和客户端密码不同 这应该在响应中返回刷新令牌和访问令牌
{"access_token":"d5deb98a-75fc-4f3a-bbfd-e5c87ca2ca6f","token_type":"bearer","refresh_token":"b2be4291-57e9-4b28-b114-feb3406e030d","expires_in":2,"scope":"read write"}
Run Code Online (Sandbox Code Playgroud)
上面的响应已经获得了访问令牌和刷新令牌。每当访问令牌过期时,您可以使用刷新令牌来获取访问令牌,如下所示:
curl -vu clientId:clientSecret 'http://your_domain_url/api/oauth/token?grant_type=refresh_token&refresh_token=refresh_token_value'
Run Code Online (Sandbox Code Playgroud)
回复:
{"access_token":"13fd30f9-f0c5-414e-9fbd-a5e2f9f3e4a7","token_type":"bearer","refresh_token":"b2be4291-57e9-4b28-b114-feb3406e030d","expires_in":2,"scope":"read write"}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用访问令牌进行服务调用
curl -i -H "Authorization: Bearer 13fd30f9-f0c5-414e-9fbd-a5e2f9f3e4a7" http://your_domain_url/api/mySecureApi
Run Code Online (Sandbox Code Playgroud)
我认为对于密码grant_type,需要 clientId 和 clientSecret 。您传递 Base64 编码的 clientId 和 clientSecret 而不是Authorization标头中的访问令牌。就像这样:
curl -H "Authorization: Bearer [base64encode(clientId:clientSecret)]" "https://yourdomain.com/oauth/token?grant_type=refresh_token&refresh_token=[yourRefreshToken]"
Run Code Online (Sandbox Code Playgroud)
我假设您首先得到这样的令牌(即使我问了,您也没有说):
curl --data "grant_type=password&username=user&password=pass&client_id=my_client" http://localhost:8080/oauth/token"
Run Code Online (Sandbox Code Playgroud)
另外,放置一个断点loadUserByUsername并检查是否为失败的刷新尝试调用它。