【发布时间】:2015-05-19 22:28:15
【问题描述】:
我使用 Spring Boot 1.2.1.RELEASE 创建了一个 Web 服务。这有我在控制器中定义的 POST ang GET 方法。我还使用来自应用程序数据库的我自己的用户凭据配置了身份验证,并且还实现了 OAuth。
这是我的 Application.class,它具有所有必要的配置。
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Service
protected static class ApplicationUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepository.findByUsername(username);
if (user == null) {
return null;
}
List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
String password = user.getPassword();
return new org.springframework.security.core.userdetails.User(username, password, auth);
}
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ApplicationUserDetailsService applicationUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(applicationUserDetailsService);
}
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.and()
.authorizeRequests()
.antMatchers("/user/**").access("#oauth2.hasScope('read')")
.antMatchers("/car/**").access("#oauth2.hasScope('read')")
.antMatchers("/transaction/**").access("#oauth2.hasScope('read')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends
AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("authorization_code", "password",
"refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.accessTokenValiditySeconds(60);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
security.allowFormAuthenticationForClients();
}
}
}
这是我的 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.web.restservice</groupId>
<artifactId>restservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>restservice</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.demo.web.restservice.Application</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!-- Added for security purposes only -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.6.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>jackson-mapper-asl</artifactId>
<groupId>org.codehaus.jackson</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这是我的一个控制器。
@RestController
@RequestMapping("/transaction")
public class TransactionController {
@Autowired
private TransactionHeaderRepository transactionHeaderRepository;
@RequestMapping("/header/{id}")
public ResponseEntity<TransactionHeader> findHeaderById(@PathVariable UUID id) {
return new ResponseEntity<>(this.transactionHeaderRepository.findById(id), HttpStatus.OK);
}
@RequestMapping(value = "/header/create", method = RequestMethod.POST)
public ResponseEntity<TransactionHeader> createHeader(@RequestBody TransactionHeader transactionHeader) {
this.transactionHeaderRepository.save(transactionHeader);
this.transactionLineRepository.save(transactionHeader.getTransactionLines());
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(value = "/header/update", method = RequestMethod.POST)
public ResponseEntity<TransactionHeader> updateHeader(@RequestBody TransactionHeader transactionHeader) {
return new ResponseEntity<TransactionHeader>(this.transactionHeaderRepository.save(transactionHeader), HttpStatus.OK);
}
@RequestMapping(value = "/header/delete", method = RequestMethod.POST)
public ResponseEntity<TransactionHeader> deleteHeader(@RequestBody TransactionHeader transactionHeader) {
this.transactionHeaderRepository.delete(transactionHeader);
return new ResponseEntity<TransactionHeader>(HttpStatus.OK);
}
}
除了我想限制用户并允许他们只更新自己的数据的部分外,一切都很好。
我该怎么做呢?这应该在控制器中完成吗?还是 Spring 提供了某种内置功能来处理这个问题?
感谢您的反馈。
【问题讨论】:
标签: security oauth authorization spring-boot