[英]Failed to find access token for token
我使用postMan,輸入請求地址http:// localhost:8011 / umrah / oauth / token?client_id = client_2&username = 1234567&password = 123456&grant_type = password&client_secret = 123456 ,單擊發送按鈕,發生錯誤,在內存中工作正常,當我想使用Jdbc令牌存儲,想法控制台錯誤:找不到令牌的訪問令牌,我找到了一些信息,但沒有找到合適的解決方案。
@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.clearAuthentication(true)
.and()
.requestMatchers().anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth/*", "/webjars/**", "/resources/**", "/swagger-ui.html"
, "/swagger-resources/**", "/v2/api-docs", "index.html", "/logout"
, "/swagger","/user/loginIn").permitAll()
.and()
.csrf()
.disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Configuration
public class OAuth2ServerConfig {
private static final String DEMO_RESOURCE_ID = "order";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout()
.clearAuthentication(true)
.and()
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
// .and()
// .requestMatchers().anyRequest()
.and()
.anonymous()
.and()
.authorizeRequests()
.antMatchers("/base/**", "/oauth/*", "/webjars/**", "/resources/**", "/swagger-ui.html"
, "/swagger-resources/**", "/v2/api-docs", "index.html", "/swagger/**","/user/loginIn").permitAll()
.anyRequest().authenticated()
.and()
.cors()
.and()
.csrf()
.disable();//配置order訪問控制,必須認證過后才可以訪問
// @formatter:on
}
}
@Configuration
@EnableAuthorizationServer
@Slf4j
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Autowired
UserDetailsService userDetailsService;
// @Autowired
// @Qualifier("myMemoryTokenStore")
// TokenStore myTokenStore;
@Autowired
private DataSource dataSource;
@Bean // 聲明TokenStore實現
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置兩個客戶端,一個用於password認證一個用於client認證
// clients.inMemory().withClient("client_1")
//// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("client_credentials")
// .scopes("select")
// .authorities("ROLE_ADMIN","ROLE_USER")
// .secret("123456")
// .and().withClient("client_2")
//// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("password", "refresh_token")
// .scopes("select")
// .accessTokenValiditySeconds(1800)
// .refreshTokenValiditySeconds(3600)
// .authorities("ROLE_ADMIN","ROLE_USER")
// .secret("123456");
clients.withClientDetails(clientDetails());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
// 2018-4-3 增加配置,允許 GET、POST 請求獲取 token,即訪問端點:oauth/token
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
// 配置TokenServices參數
DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(true);
// 復用refresh token
tokenServices.setReuseRefreshToken(true);
tokenServices.setRefreshTokenValiditySeconds(3600);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 1天
endpoints.tokenServices(tokenServices);
super.configure(endpoints);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//允許表單認證
oauthServer.allowFormAuthenticationForClients();
}
}
@FrameworkEndpoint
public class LogoutEndpoint {
@Qualifier("myMemoryTokenStore")
@Autowired
private TokenStore tokenStore;
@RequestMapping(value = "/oauth/logout", method= RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void logout(HttpServletRequest request, HttpServletResponse response){
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
String tokenValue = authHeader.replace("Bearer", "").trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
tokenStore.removeAccessToken(accessToken);
}
}
}
}
@Service("userService")
@Slf4j
public class UserService implements UserDetailsService {
@Resource(name = "service.UserService")
private com.jolly.atplan.umrah.service.service.UserService userService;
@Override
public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
log.info("LoginID : {}",loginId);
User user = userService.getUserByLoginId(loginId);
if(Objects.isNull(user)){
throw new UsernameNotFoundException("User " + loginId + " was not found in the database");
}
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
// List<UserAuthority> authorityList = userAuthorityDao.getAuthorityListByUser(loginId);
// for (UserAuthority authority : authorityList) {
// GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getAuthority());
// grantedAuthorities.add(grantedAuthority);
// }
//返回一個SpringSecurity需要的用戶對象
return new org.springframework.security.core.userdetails.User(
user.getLoginId(),
user.getPwd(),
grantedAuthorities);
}
}
已經在工作,我重寫了JdbcTokenStore的readAccessToken方法,感謝oauth2的Rest服務:無法找到令牌的訪問令牌
`public class JdbcTokenStores extends JdbcTokenStore {
private static final Log LOG = LogFactory.getLog(JdbcTokenStores.class);
public JdbcTokenStores(DataSource dataSource) {
super(dataSource);
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
OAuth2AccessToken accessToken = null;
try {
accessToken = new DefaultOAuth2AccessToken(tokenValue);
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for token "+tokenValue);
}
}
catch (IllegalArgumentException e) {
LOG.warn("Failed to deserialize access token for " +tokenValue,e);
removeAccessToken(tokenValue);
}
return accessToken;
}
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.