我已经通过以下请求接收了访问令牌。
curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic dHJ1c3RlZC1jbGllbnQ6c2VjcmV0" -H "Cache-Control: no-cache" -H "Postman-Token: 99a69c90-d7f0-64ae-bc8e-f682e84c58c3" "http://localhost:9090/oauth/token?grant_type=password&username=admin&password=admin123"
以下是回复
{
"access_token": "597147a1-bf8a-47f5-bd22-74ea1cd1df8f",
"token_type": "bearer",
"refresh_token": "de680b4a-e94e-460a-8853-be1aa5a264a3",
"expires_in": 4972,
"scope": "read write trust"
}
但是当我发送带有访问权限的请求获得403时。 发送get请求时出错。
{
"timestamp": 1477034937446,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/user/customers"
}
发送获取请求时。
curl -X GET -H "Authorization: Bearer 597147a1-bf8a-47f5-bd22-74ea1cd1df8f" -H "Cache-Control: no-cache" -H "Postman-Token: 7d8dfa60-8aeb-90ad-1bbe-433b52ef8306" "http://localhost:9090/user/customers"
我使用了Mongo DB,Morphia作为用户访问。 Redis用作令牌存储。但身份验证不起作用。
以下是弹簧相关配置
@Configuration
@EnableAuthorizationServer
@ComponentScan(value = "com.guddi.muneeb")
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static String REALM = "MUNEEB_OAUTH_REALM";
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT","ADMIN")
.scopes("read", "write", "trust").resourceIds("MUNEEB_OAUTH_REALM")
.secret("secret")
.accessTokenValiditySeconds(6000).//Access token is only valid for 10 minutes.
refreshTokenValiditySeconds(12000);//Refresh token is only valid for 20 minutes.
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm(REALM + "/client");
}
}
的OAuth:
@Configuration
@EnableWebSecurity
@ComponentScan(value = "com.guddi.muneeb")
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
ClientDetailsService clientDetailsService;
@Autowired
SecUserDetailsService userDetailsService;
@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/user/**").authenticated()
//.anyRequest().hasRole("ADMIN").and()
//.anyRequest().permitAll()
//.authorizeRequests()
.antMatchers("/oauth/token").permitAll();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public JedisConnectionFactory jedisConnectionFactory;
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(jedisConnectionFactory);
}
@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
资源服务器配置
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "muneeb_resource";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
//anonymous().disable()
.requestMatchers().antMatchers("/muneeb/**")
//.requestMatchers().antMatchers("/muneeb/user/**")
//.requestMatchers().antMatchers("/muneeb/admin/**")
.and().authorizeRequests()
//.antMatchers("/muneeb/admin/**").access("hasRole('ADMIN')")
//.antMatchers("/muneeb/user/**").access("hasRole('ADMIN')")
.antMatchers("/muneeb/**").access("hasRole('ADMIN')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
//.anyRequest().permitAll();
}
}
UserDetails实现
@Service
public class SecUserDetails implements UserDetails {
private User user;
public SecUserDetails() {
super();
}
public SecUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (String role : user.getRoles()) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
authorities.add(grantedAuthority);
}
//LOGGER.debug("user authorities are " + authorities.toString());
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return user.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
return user.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return user.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return user.isEnabled();
}
请帮帮我。如果我遗失了什么。
提前致谢