我使用的是spring boot oauth2安全性,grant\u type=authorization\u代码流。
我已经成功地收到了oauth/authorize请求的代码响应,然后在oauth/token请求中传递了该代码,还成功地收到了access\u token响应。
现在,我想用request-mapping/admin/调用api,它给出了错误401。我已经为任何角色提供了访问此(/admin/)url的权限。但它忽视或不起作用。
我已经给出了我所有的配置在这里终于屏幕后。
当我向postman请求/admin/getdata时,它将抛出401未经授权的错误。
在这里,我一步一步地发布了postman的所有屏幕截图,请注意,因为它是localhost,在使用oauth/authorize获得代码值之后,我已经从postman手动请求了oauth/token。
步骤1:获取包含详细信息的新访问令牌
步骤2:获取用于身份验证的登录表单
步骤3收到响应代码
步骤4请求具有相同代码和状态值的oauth/令牌,并成功接收具有其他值的访问令牌
步骤5请求控制器url/admin/api/getdata以access token pass作为承载,在头中接收到\u access \u token,得到401个未授权错误
我正在使用clientdetailservice窗体数据库身份验证。我的完整代码如下。
Web安全配置ConfigureAdapter的配置
@Configuration
@EnableWebSecurity
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationService authenticationService;
@Autowired
private PasswordEncoder passwordEncoder;
@Bean(name = "myAuthenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authenticationService).passwordEncoder(passwordEncoder);
}
}
resourceserverconfigureradapter的配置
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Override
public void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
// Open access to all
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/oauth/authorize", "/login", "/oauth/token", "/oauth/logout")
.permitAll();
http.formLogin().permitAll().and().logout().permitAll();
// Access to Admin
http.authorizeRequests().antMatchers("/admin/**").hasAuthority("ADMIN");
// All other request are authenticated
http.authorizeRequests().anyRequest().authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("resource_id").tokenStore(tokenStore).stateless(false);
}
}
authorizationserverconfigureradapter的配置
@Configuration
@EnableAuthorizationServer
public class OAuth2Server extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
public AuthenticationManager authenticationManager;
@Autowired
private AuthenticationService authenticationService;
@Autowired
private DynamicClientDetailService dynamicClientDetailService;
@Autowired
private TokenEnhancer tokenEnhancer;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore).tokenEnhancer(tokenEnhancer)
.userDetailsService(authenticationService).setClientDetailsService(dynamicClientDetailService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(dynamicClientDetailService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
}
clientdetailsservice的配置
@Configuration
public class DynamicClientDetailService implements ClientDetailsService {
@Autowired
private DynamicClientDetailsRepository dynamicClientDetailsRepository;
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
DynamicClientDetails client = dynamicClientDetailsRepository.findByClientId(clientId);
BaseClientDetails base = new BaseClientDetails(client.getClientId(), client.getResourceIds(), client.getScope(),
client.getAuthorizedGrantTypes(), client.getAuthorities());
base.setClientSecret(client.getClientSecret());
base.setAccessTokenValiditySeconds(client.getAccessTokenValiditySeconds());
base.setRefreshTokenValiditySeconds(client.getRefreshTokenValiditySeconds());
base.setAutoApproveScopes(getScopes(client.getScope()));
base.setRegisteredRedirectUri(getRegisteredRedirectURL(client));
return base;
}
/**
* Get registered redirect URL
*
* @param client
* @return
*/
private Set<String> getRegisteredRedirectURL(DynamicClientDetails client) {
return StringUtils.isEmpty(client.getRegisteredRedirectUri()) ? null
: Arrays.stream(client.getRegisteredRedirectUri().split(",")).collect(Collectors.toSet());
}
/**
* Get collection from string
*
* @param scope
* @return
*/
private Collection<String> getScopes(String scope) {
Collection<String> scopes = new ArrayList<String>();
if (StringUtils.isEmpty(scope))
return scopes;
String[] scopesArr = scope.split(",");
if (scopesArr.length == 0)
return scopes;
scopes = Arrays.asList(scopesArr);
return scopes;
}
}
userdetailsservice的配置
@Configuration
public class AuthenticationService implements UserDetailsService {
@Autowired
private LoginCredentialService loginCredentialService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LoginCredential loginCredential = loginCredentialService.getLoginCredentialByEmail(username);
return new org.springframework.security.core.userdetails.User(loginCredential.getEmail(),
loginCredential.getPassword(), loginCredential.getIsActive(), !loginCredential.getIsDelete(),
loginCredential.isVerified(), true, getSimpleGrantedAuthorities(loginCredential.getRole().toString()));
}
private Collection<GrantedAuthority> getSimpleGrantedAuthorities(String role) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority(role));
return grantedAuthorities;
}
}
控制器代码
@RestController
@RequestMapping("/admin/api")
public class DataController {
@GetMapping("/getData")
public ResponseEntity<String> getData() throws Exception {
return ResponseEntity.ok("Success");
}
}
创建客户端详细信息查询
CREATE TABLE public.dynamic_client_details
(
id bigint NOT NULL DEFAULT nextval('dynamic_client_details_id_seq'::regclass),
access_token_validity_seconds integer,
authorities character varying(255),
authorized_grant_types character varying(255),
auto_approve boolean NOT NULL,
client_id character varying(255),
client_secret character varying(255),
refresh_token_validity_seconds integer,
registered_redirect_uri character varying(255),
resource_ids character varying(255),
scope character varying(255),
scoped boolean NOT NULL,
secret_required boolean NOT NULL,
CONSTRAINT dynamic_client_details_pkey PRIMARY KEY (id),
);
带值的客户端详细信息的插入查询
INSERT INTO public.dynamic_client_details(id, access_token_validity_seconds, authorities, authorized_grant_types, auto_approve, client_id,
client_secret, refresh_token_validity_seconds, registered_redirect_uri, resource_ids, scope, scoped, secret_required)
VALUES (1, 50000, 'ROLE_ADMIN', 'password,authorization_code,refresh_token', true, 'MY_CLIENT_ID',
'MY_ENCODED_SECRET', 50000, 'https://oauth.pstmn.io/v1/callback', 'resource_id', 'read,write,trust', true, true);
数据库登录表中角色的用户详细信息
email = abc@gmail.com
password = MY_PASSWORD
role = ROLE_ADMIN
请指导我应该改变什么与授权用户调用api。
提前谢谢。
暂无答案!
目前还没有任何答案,快来回答吧!