【发布时间】:2017-04-13 21:32:10
【问题描述】:
我有一个 Spring Boot 应用程序。我正在尝试为该应用程序实施 OAuth2 授权。我已经按照本教程https://spring.io/guides/tutorials/spring-boot-oauth2/ 启用授权服务器部分。虽然我能够成功地从身份验证服务器获取访问令牌,但当我尝试发送这些令牌以请求我的资源服务器时,它会在控制台中出现 Unauthorized access 错误。
org.springframework.security.access.AccessDeniedException: Access is denied
虽然我稍后会将授权服务器和资源服务器分开,但出于初始目的,两者的单个应用程序都可以工作。
@Configuration
@EnableAuthorizationServer
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(Application.baseURL + "/user/register");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().authenticated()
.and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
.and().csrf().disable();
}
}
用于用户身份验证
@Configuration
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Loggable
private static Logger logger;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Session session = Hibernate.sessionFactory.openSession();
try {
UserPasswordDTO userPasswordDTO = new UserPasswordModel().getByEmailId(session, username);
return new SimsmisUser(username, userPasswordDTO.hashedPassword, true, true, true, true,
AuthorityUtils.createAuthorityList("USER"), userPasswordDTO.userId);
}
catch (InvalidIdException e) {
throw new UsernameNotFoundException(e.getMessage());
}
finally {
if (session != null) {
try {
session.close();
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
}
};
}
}
如何使用访问令牌与资源服务器通信? 任何示例都会有所帮助。
【问题讨论】:
标签: spring-boot oauth-2.0 spring-security-oauth2