使用Spring Boot Security和本地数据库(h2)验证路径

时间:2019-04-03 08:39:45

标签: angular spring spring-boot spring-security h2

我正在为一个具有本地h2数据库的spring-boot项目实现简单登录,该数据库存储用户凭据:

application.yaml:

spring:
  application:
    name: user-service
  datasource:
    url: jdbc:h2:./dbUser
    username: sa
    password:
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true
      path: /h2-console/user
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        show_sql: true

我正在使用Spring Security创建用于验证用户并允许他们访问API的登录名。为此,我加入了一项服务,该服务会在数据库中查找用户并返回该用户(如果有):

UserAuthService.java:

@Service
public class UserAuthService implements UserDetailsService{

    @Autowired
    private UserCredentialsRepository userCredentialsRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username){
        UserCredentials userCredentials = userCredentialsRepository.findByUsername(username);
        if(userCredentials==null) throw new UsernameNotFoundException(username);
        Set<GrantedAuthority> grantedAuthoritySet = new HashSet<>();
        grantedAuthoritySet.add(new SimpleGrantedAuthority("USER"));

        return new User(userCredentials.getUsername(), userCredentials.getPassword(), grantedAuthoritySet);
    }
}

UserCredentialsRepository.java

public interface UserCredentialsRepository extends CrudRepository<UserCredentials, Long> {
    UserCredentials findByUsername(String username);

    UserCredentials findByUserId(Long id);
}

我的Web安全配置类: WebSecurityConfig.java:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{

        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/users").permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/h2-console/user/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
        http.headers().frameOptions().disable();
    }
}

我用Angular创建了一个登录页面,该页面使用了API /底层控制器功能,并通过http.post请求提供了凭据输入。

@RequestMapping("/login")
public boolean login(@RequestBody UserCredentials userCredentials) {
    UserDetails userDetails = userAuthService.loadUserByUsername(userCredentials.getUsername());
    return
            userCredentials.getUsername().equals(userDetails.getUsername()) && userCredentials.getPassword().equals(userDetails.getPassword());
    }

我的问题: 对数据库的访问以及通过上述控制器功能的响应都可以正常工作,但如果上述控制器功能返回 true ,我不知道如何授权所有路径。

0 个答案:

没有答案