【问题标题】:How to implement specific authorization by user level in spring boot?spring boot中如何实现用户级别的特定授权?
【发布时间】: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


    【解决方案1】:

    为此,您可以创建自己的自定义注释 (@Useridentifier) 并使用它映射到 UserDetails.UserId(您的用户 PK)。将它放在包含用户 PK 的 DTO 上。

    接下来,您可以创建另一个注释 (@Useridentifiercheck) 放置在您的端点上(如 requestMapping)。如果值不匹配,则抛出异常并返回 401 或将 userId 替换为 OAuth 属性中的 userId(如果您将 userId 存储在 OAuth 数据中)。

    注意:所有这些也可以通过服务和一些反射来完成,但我喜欢注释:)

    失败的地方 如果你有一个休息点更新没有 UserId 的 FK 表,那么这个想法就落空了。

    示例

    table - User { long userId; nvarchar name; long address_fk; }
    table - Address { long addressId; nvarchar postcode; }
    

    在这里我们可以更新地址,但是如果没有一些加入来给我们 userId,我们不知道我们是否被“授权”来编辑地址。

    服务器端问题 需要小心为管理员删除此功能,否则,他们将无法更新其他人的数据以太......

    网关 API

    另一个例子是创建一个靠近 UI 的网关 API(例如 ExpressJS 服务 React 和自定义 API)

    UI 会话可以存储在 Express 中,并且会过滤以确保任何自动更新请求都具有“正确的”用户 ID。

    例如:一个坏人发送以下 JSON

    put: { userId: 69, password: powned, firstname: Paul }
    

    Express API 采用 DTO 并去除未经授权的输入(用户 ID、密码)。请注意,在这种情况下,请求将被传递到 API,将“传入”的 userId 替换为正确的会话值。

    核心 API 将位于 VPN 防火墙后面,并使用客户 OAuth 令牌进行限制。

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2018-08-18
      • 1970-01-01
      • 2021-05-16
      • 2013-11-02
      • 2021-12-10
      • 2020-03-20
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多