1
我試圖用OAuth 2創建一個服務器,但我遇到了問題。我配置了OAuth,用戶可以授權並獲取令牌,但REST方法始終可訪問,例如,用戶可以在未授權時使用POST方法。在Java中配置OAuth 2 Spring Boot
如何配置OAuth,以便REST方法僅在用戶授權時運行?
這是怎麼了我的一些代碼,看起來像(我用這個example code):
OAuthConfiguration類
@Configuration
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "restservice";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
// @formatter:off
resources
.resourceId(RESOURCE_ID);
// @formatter:on
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/users").hasRole("ADMIN")
.antMatchers("/greeting").authenticated();
// @formatter:on
}
}
AuthorizationServerConfiguration類:
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// @formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// @formatter:on
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("123456");
// @formatter:on
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
休息控制器:
@RestController
@RequestMapping("/ABC")
final class Controller {
@Autowired
Repository repository;
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
int create(@RequestBody @Valid Data myData) {
repository.create(myData);
return 1;
}
@RequestMapping(value = "{number}", method = RequestMethod.GET)
Data findByNumber(@PathVariable("number") String number) {
Data data = repository.findByNumber(number);
return data;
}
@RequestMapping(value = "{number}", method = RequestMethod.PUT)
int update(@RequestBody @Valid Data myData) {
int rows = repository.update(myData);
return 1;
}
@RequestMapping(value = "{number}", method = RequestMethod.DELETE)
int delete(@PathVariable("number") String number) {
repository.delete(serialNumber);
return 1;
}
}
謝謝你,它的工作!一個小題目,但是你也許知道用戶輸入授權的密碼是否可以從服務器訪問? – Someone
我不確定你的新問題的答案。取決於您是否將resourceServer和authorizationServer視爲同一臺服務器。資源服務器應該不需要知道有關憑證。如果認爲正確,請接受上面的答案。謝謝 – sdoxsee